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 −

 Live Demo

def add_upto_n(n):
   res = (n * (n - 1)) / 2
   return res
n = 6
print(int(add_upto_n(n)))

Input

6

Output

15

Updated on: 25-Aug-2020

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements