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:

InputOutput
1055
206765

Your solution

Program.cs โ€” 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.

Solution (try first!)
int n = int.Parse(Console.ReadLine());
int a = 0, b = 1;
for (int i = 0; i < n; i++) { int t = a + b; a = b; b = t; }
Console.WriteLine(a);

You've reached the top of the problem set โ€” revisit the list, or read Lesson 5 on when recursion IS the right tool.