Computing the Nth Fibonacci Number

suggest change

The following method computes the Nth Fibonacci number using recursion.

public int fib(final int n) {
    if (n > 2) {
        return fib(n - 2) + fib(n - 1);
    }
    return 1;
}

The method implements a base case (n <= 2) and a recursive case (n > 2). This illustrates recursion for a recurrence relation. For n <= 0 it returns 1, which is not a Fibonacci number, and the int result overflows for large n.

This example is inefficient: each call makes two further calls, so the number of calls grows exponentially with n. This implementation is O(2^n). An equivalent loop is O(n). A closed form can be evaluated in a constant number of floating-point operations, but rounding limits how large n can be.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents