Video in progress

Why is computing a Fibonacci number with plain recursion so slow, and how do you fix it?

fib(n-1) + fib(n-2) computes the same values over and over, and the number of calls grows roughly as 2ⁿ. Remembering the results (memoization) or using a plain loop brings it down to O(n).

📖 Answer

static long fib(int n) {
    if (n < 2) return n;
    return fib(n - 1) + fib(n - 2);
}

When fib(5) is called, fib(3) is computed twice and fib(2) three times. At n = 45 that's several seconds, and at n = 60 you won't wait for it.

The simplest fix is to keep the previous two values and walk with a loop:

static long fibFast(int n) {
    long prev = 0, cur = 1;
    if (n == 0) return 0;
    for (int i = 2; i <= n; i++) {
        long next = prev + cur;
        prev = cur;
        cur = next;
    }
    return cur;
}

Time is O(n), memory is O(1). If you want to keep the recursive form, write the results into a long[] memo array; this is the very first example of dynamic programming.

One catch: long holds values up to fib(92), after which it overflows. If you need larger values, use BigInteger.