Given a number n, find n-th Fibonacci Number. Note that F0 = 0, F1 = 1, F2 = 2, …..
Input : n = 5 Output : 5 Input : n = 10 Output : 89
We have discussed below recursive solution in method 4 of Program for Fibonacci numbers.
F = |1, 1| |1, 0| M = |1, 1| |1, 0| F[n][n] = fib(n) | fib(n-1) ------------------ fib(n-1)| fib(n-2)
In this post an iterative method is discussed that avoids extra recursion call stack space. We have also used bitwise operators to further optimize. In the previous method, we divide the number with 2 so that at the end we get 1 and then we start the multiplication process
In this method we get the second MSB then start to multiply with FxF matrix then if bit is set then multiply again FxM matrix and so on. then we get the final result.
Approach : 1. First get the MSB of a number. 2. while (MSB > 0) multiply(F, F); if (n & MSB) multiply(F, M); and then shift MSB till MSB != 0
Time Complexity :- O(logn) and space complexity :- O(1).
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Improved By : Mithun Kumar
- Program for Fibonacci numbers
- Divisibility by 12 for a large number
- Write a C program to reverse digits of a number
- Largest number that is not a perfect square
- Average of first n even natural numbers
- Number of Permutations such that no Three Terms forms Increasing Subsequence
- Check if the first and last digit of the smallest number forms a prime
- Print all substring of a number without any conversion
- Complement of a number with any base b
- Check if Decimal representation of an Octal number is divisible by 7