Medium ยท sliding pair
Fibonacci Number
F(0)=0, F(1)=1, F(n)=F(nโ1)+F(nโ2). Compute it with a sliding pair โ then compare with the exponential recursion from Lesson 5.
Problem
Input: one integer n (0 โค n โค 45).
Output: F(n), where F(0) = 0 and F(1) = 1. (F(45) = 1,134,903,170 โ the largest that fits in an int.)
Sample:
| Input | Output |
|---|---|
10 | 55 |
20 | 6765 |
Your solution
Custom input for "Run my input"
Judging runs entirely in your browser against hidden tests. Your code is saved locally as you type. Ctrl+Enter judges.
Stuck? Hints
Hint 1 โ the sliding pair
Keep two variables a = 0, b = 1. Each pass: int t = a + b; a = b; b = t;. After n passes, a is F(n).
Hint 2 โ why not the recursion from Lesson 5?
Fib(45) recursively makes ~2 billion calls. The sliding pair makes 45. Same math, exponentially different cost โ that's algorithmic thinking.