![]() |
VOOZH | about |
Given a number n, print n-th Fibonacci Number, using Binet's Formula.
Examples:
Input: n = 5
Output: 1
Explanation: The 5th Fibonacci number in the sequence (0, 1, 1, 2, 3, 5, ...) is 1.Input: n = 9
Output: 34
Explanation: The 9th Fibonacci number in the sequence (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...) is 34.
Binet's Formula provides a closed-form expression for the Fibonacci sequence:
Fn = (1 / √5) * (φ^n - ψ^n)
where:
- φ (phi) = (1 + √5) / 2 (Golden Ratio)
- ψ (psi) = (1 - √5) / 2 (Negative Reciprocal of φ)
Although Binet’s Formula is mathematically correct, it is rarely used in practice due to floating-point precision errors. These errors arise because of the irrational numbers involved in the computation.
- The formula produces accurate results only up to n < 71 due to rounding errors.
- For n = 71, using the floor function instead of rounding provides the correct result.
- However, for n ≥ 72, even the floor function fails.
Example:
Correct value for F(72) = 498454011879264
Binet’s Formula computes 498454011879265 (incorrect due to precision loss).
Instead of Binet’s Formula, iterative methods, matrix exponentiation, or fast doubling techniques are preferred for computing large Fibonacci numbers efficiently and accurately.
However, if using Binet’s Formula for small values of n, the following implementation can be used:
Fn = (1 / √5) * φ^n
where:
- φ (phi) = (1 + √5) / 2 (Golden Ratio)
For practical applications, integer-based methods are recommended to avoid precision errors.
Below is the implementation of the above approach:
Fibonacci(5) = 5 Fibonacci(9) = 34
Time Complexity: O(log n), this is due to the pow function, which uses exponentiation by squaring.
Auxiliary Space: O(1), as only a few variables are used, with no extra data structures.