Python Program for the n-th Fibonacci number using recursion

Using recursion we have one way to solve this problem, let us take a look at it.

Method 1: Using multiple conditionals

def get_nth_fibonacci(n):
	if n<= 0:
		print("Incorrect input")
python-program-f
	elif n == 1:
		return 0

	elif n == 2:
		return 1
	else:
		return get_nth_fibonacci(n-1)+get_nth_fibonacci(n-2)
n = int(input("Enter the n-th fibonacci number you want: "))
print("The",n,"get_nth_fibonacci number is: ",get_nth_fibonacci(n))

Output:

Enter the n-th fibonacci number you want: 10
The 10 get_nth_fibonacci number is:  34

Explanation:

This is the most basic approach to solving this problem. We used conditional statements to check if the number is 0, if it is zero then we print the “Incorrect input”. In the same way, we defined conditions for 1 and 2 also. Now for the rest of the numbers, we used the function again and computed the value of n-1 and n-2, and finally added them.

Method 2: Using limited conditionals

fibo = [0, 1]

def get_nth_fibonacci(n):
	if n<0:
		print("Incorrect input")
	elif n<= len(fibo):
		return fibo[n-1]
	else:
		temp_fib = get_nth_fibonacci(n-1)+get_nth_fibonacci(n-2)
		fibo.append(temp_fib)
		return temp_fib

print(get_nth_fibonacci(n))

n = int(input("Enter the n-th fibonacci number you want: "))
print("The",n,"get_nth_fibonacci number is: ",get_nth_fibonacci(n))

Output:

Enter the n-th fibonacci number you want: 10
The 10 get_nth_fibonacci number is:  34

Explanation:

The only difference between the previous method and this one is that we did not individually use the conditional for 1 and 2, instead we computed the length of the fibo list and simply returned the value that comes after computing fibo[n-1]. This will only be done if n is smaller than the length of the fibo.

These above are the two methods using which we can solve the given problem.


Share:

Author: Dhvanil V