Python mathematical sequence
I have to write code to manually input n number and code should find that n member of sequence.n should be natural number. Formula for that sequence is
f(n)=(f(n-1))²-1
First member is 2 second 3 third 8 and every next is one less than square of number before. The code should print that n member of sequence which is inputted. For example
In:3
Out:8
In:4
Out:63
I wrote code but it don't work
n = int(input("'input n:"))
def f(n):
if n < 0:
print('Undefined')
else:
return (f(n - 1) ** 2) - 1
print(f(n))
Solution 1:
In recursion, you need to return a definite value for the stop index.
Here you just have to write in your code that the first value of the sequence is 2:
def f(n):
if n < 0:
raise ValueError('Undefined') # better to raise to make sure to abort
elif n == 0:
return 2
else:
return (f(n - 1) ** 2) - 1
That is enough for f(1)
to return 3 and f(2)
to return 8...