Write a program to calculate the nth Fibonacci number where n is a given positive number.

Fibonacci’s sequence is characterized by the fact that every number after the first two is the sum of the two preceding ones. For example, consider the following series:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, … and so on.

As we can see above, each subsequent number is the sum of the previous two numbers. The starting point of the sequence is sometimes considered 1, resulting in the first two numbers in the Fibonacci sequence as 1 and 1.

Practice this problem

The following recurrence relation defines the sequence Fn of Fibonacci numbers:

F{n} = F{n-1} + F{n-2} with base values F(0) = 0 and F(1) = 1.

 
Following is the naive implementation in C, Java, and Python for finding the nth member of the Fibonacci sequence:

C


Download  Run Code

Output:

F(n) = 21

Java


Download  Run Code

Output:

F(n) = 21

Python


Download  Run Code

Output:

F(n) = 21

We can easily convert the above recursive program into an iterative one. If we carefully notice, we can directly calculate the value of F(i) if we already know the values of F(i-1) and F(i-2). So if we calculate the smaller values of fib first, we can easily build larger values. This approach is also known as the bottom-up approach and widely used to solve dynamic programming problems.

C


Download  Run Code

Output:

F(n) = 21

Java


Download  Run Code

Output:

F(n) = 21

Python


Download  Run Code

Output:

F(n) = 21

The time complexity of the above iterative solution is O(n) since it contains a loop that repeats n-1 times, but it only takes constant space, in contrast to the recursive approach, which requires O(n) space for recursion (call stack) and exponential time as many subproblems are recalculated repeatedly. We can also improve the time complexity of the recursive approach by saving values that have already been calculated. This approach is discussed below in C++, Java, and Python:

C++


Download  Run Code

Output:

F(n) = 21

Java


Download  Run Code

Output:

F(n) = 21

Python


Download  Run Code

Output:

F(n) = 21