![]() |
VOOZH | about |
Given a non-negative integer n, your task is to find the nthFibonaccinumber. The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1. The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
The Fibonacci sequence is defined as follows:
Examples:
Input: n = 5
Output: 5
Explanation: The 5th Fibonacci number is 5.
Input: n = 0
Output: 0
Explanation: The 0th Fibonacci number is 0.
The Fibonacci sequence can be approximated using the golden ratio: where, .Since, the ratio of consecutive Fibonacci numbers approaches φ, we can use this property to compute the next number.
Till 4th term, the ratio is not much close to golden ratio (as 3/2 = 1.5, 2/1 = 2, ...). So, we will consider from 5th term to get next fibonacci number. To find out the 9th fibonacci number f9 (n = 9). Hence, this method is reliable only from the 5th term onward. After:
Note:
Fibonacci Number: 5
Time complexity: O(n)
Auxiliary space: O(1)