![]() |
VOOZH | about |
The Fibonacci series is a sequence in which each number is the sum of the previous two numbers. The series starts with 0 and 1, and the remaining terms are generated using the relation:
F(n)=F(nā1)+F(nā2)
where:
Example:
Input: 5
Output: 5
Explanation: In the Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13..., the value at index 5 is 5 (using 0-based indexing).
There are multiple approaches to find the nth Fibonacci number in C++. Each method has different time and space complexities.
The simplest way to find the nth Fibonacci number is by using recursion. In this method, the function repeatedly calls itself to calculate previous Fibonacci numbers.
Approach:
5
Explanation: The function recursively calculates the Fibonacci value by adding the previous two Fibonacci numbers.
The recursive solution can be optimized by passing the previous two Fibonacci numbers as parameters. This avoids repeated calculations.
Approach:
5
Explanation: Instead of recalculating previous Fibonacci numbers, the function carries forward the last two values in each recursive call.
The iterative approach using loops is one of the most efficient and commonly used methods.
Approach:
5
Explanation: The loop continuously updates the last two Fibonacci numbers until the required term is found.
In this approach, the Fibonacci series is represented using a transformation matrix based on the Fibonacci relation:
F(n)=F(nā1)+F(nā2)
where:
This method efficiently calculates the nth Fibonacci number by raising the transformation matrix to the power (n - 1). Matrix exponentiation uses the divide-and-conquer technique to compute powers quickly, making it much faster for large values of n.
5
Explanation: Matrix exponentiation reduces repeated calculations by using divide-and-conquer techniques.