Problem 9
Nth Fibonacci Number
Easy · 10 pts · Math, Dynamic Programming, Recursion
Problem
The Fibonacci sequence starts with F(0) = 0 and F(1) = 1, and every later term is the sum of the two before it: F(n) = F(n - 1) + F(n - 2). The first terms are 0, 1, 1, 2, 3, 5, 8, 13, 21, ... Given N, print F(N). A loop that keeps only the last two values is fast and simple. A plain recursive function that calls itself twice per step is far too slow for N near 45, because it recomputes the same values again and again.
Input
A single integer N.
Output
Print F(N).
Constraints
0 <= N <= 45
Example input
6
Example output
8
Explanation
Building the sequence: F(0) = 0, F(1) = 1, F(2) = 1, F(3) = 2, F(4) = 3, F(5) = 5, F(6) = 3 + 5 = 8. So for N = 6 the answer is 8.