The nth Fibonacci number
Return the nth Fibonacci number, where F(0) = 0, F(1) = 1 and every next one is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, …
Write fibonacci(n) in Python, fibonacci(n) in JavaScript or TypeScript, or int fibonacci(int n) in C. Level: Medium.
Examples
Input: n = 6 Output: 8
Input: n = 10 Output: 55
- 0 ≤ n ≤ 70
- A plain recursive answer is too slow for the bigger tests: watch it run to see why
Hint
Keep just the last two numbers in two variables and move them forward n times: a, b = b, a + b. The recursive version recomputes the same numbers again and again.
The approach, step by step
- a = 0, b = 1, k = 0
- k < n?
- a, b = b, a + b
- k = k + 1
- Return a