Suppose we have a number n. We have to find the nth Fibonacci term by defining a recursive function.
So, if the input is like n = 8, then the output will be 13 as first few Fibonacci terms are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...
To solve this, we will follow these steps −
- Define a function solve() . This will take n
- if n <= 2, then
- return n - 1
- otherwise,
- return solve(n - 1) + solve(n - 2)
Example
Let us see the following implementation to get better understanding −
def solve(n): if n <= 2: return n - 1 else: return solve(n - 1) + solve(n - 2) n = 8 print(solve(n))
Input
8
Output
13