easymathdynamic-programming

Fibonacci

Read N and print the Nth Fibonacci number. F(0) = 0, F(1) = 1, F(N) = F(N-1) + F(N-2).

Problem

Statement

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... — each number is the sum of the previous two.

Three canonical approaches, in increasing sophistication:

Recursion (bad — O(2^N)) demonstrates the definition literally.

Iteration (good — O(N) time, O(1) memory) is the pragmatic solution.

Matrix exponentiation (O(log N)) is what you use if N is really big.

Worked cases

Examples

Input
0
Output
0
Input
10
Output
55
Input
50
Output
12586269025
Bounds

Constraints

  • 0 ≤ N ≤ 90 (fits in signed 64-bit).
Reference

Sample solutions

Runnable starter code. Click "Try in playground" to open pre-loaded with the test fixtures.

Python
n = int(input())
a, b = 0, 1
for _ in range(n):
    a, b = b, a + b
print(a)
Java
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        long a = 0, b = 1;
        for (int i = 0; i < n; i++) { long t = a + b; a = b; b = t; }
        System.out.println(a);
    }
}
C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n; cin >> n;
    long long a = 0, b = 1;
    for (int i = 0; i < n; ++i) { long long t = a + b; a = b; b = t; }
    cout << a << "\n";
}
Also try