
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Nth Term of a Given Recurrence Relation in Python
Suppose we have a sequence of numbers called bn, this is represented using a recurrence relation like b1=1 and bn+1/bn=2n . We have to find the value of log2(bn) for a given n.
So, if the input is like 6, then the output will be 5 as log2(bn) = (n * (n - 1)) / 2 = (6*(6-1))/2 = 15
We can solve this problem by solving this relation as follows −
bn+1/bn = 2n
bn/bn-1 = 2n-1
…
b2/b1 = 21 , If we multiply all of above, we can get
(bn+1/bn).(bn/bn-1)……(b2/b1) = 2n + (n-1)+……….+1
So, bn+1/b1 = 2n(n+1)/2
As 1 + 2 + 3 + ………. + (n-1) + n = n(n+1)/2
So, bn+1 = 2n(n+1)/2 * b1; We are assuming that initial value b1 = 1
So, bn+1 = 2n(n+1)/2
After substituting (n+1) for n, we get,
bn = 2n(n-1)/2
By taking log both sides, we get,
log2(bn) = n(n-1)/2
Example
Let us see the following implementation to get better understanding −
def add_upto_n(n): res = (n * (n - 1)) / 2 return res n = 6 print(int(add_upto_n(n)))
Input
6
Output
15