ZetCode

Java Fibonacci

last modified February 24, 2024

In this article we show how to calculate Fibonacci series in Java. We create several algorithms for calculating Fibonacci series.

Fibonacci series is a sequence of values such that each number is the sum of the two preceding ones, starting from 0 and 1. The beginning of the sequence is thus: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...

In this article we show several ways to generate a fibonacci series in Java. Since fibonacci series is a sequence of infinite numbers, we use BigInteger type for calculations.

Fibonacci classic loop example

The first algorithm uses a for loop.

Main.java
import java.math.BigInteger;

BigInteger fibonacci(int n) {

    if (n <= 1) {
        return BigInteger.valueOf(n);
    }

    BigInteger previous = BigInteger.ZERO, next = BigInteger.ONE, sum;

    for (int i = 2; i <= n; i++) {

        sum = previous;
        previous = next;
        next = sum.add(previous);
    }

    return next;
}

void main() {

    for (int i = 0; i <= 99; i++) {

        BigInteger val = fibonacci(i);
        System.out.println(val);
    }
}

The example prints first one-hundred values of a Fibonacci series.

Fibonacci recursive example

In the second example, we calculate the Fibonacci series using a recursive algorithm where the fibonacci method calls itself to do the calculation.

Main.java
import java.math.BigInteger;

BigInteger fibonacci(int n) {

    if (n == 0 || n == 1) {

        return BigInteger.ONE;
    }

    return fibonacci(n - 2).add(fibonacci(n - 1));
}

void main() {

    for (int i = 0; i < 10; i++) {
        System.out.println(fibonacci(i));
    }
}

The example calculates the first ten values of a fibonacci sequence.

BigInteger fibonacci(int n) {

    if (n == 0 || n == 1) {

        return BigInteger.ONE;
    }

    return fibonacci(n - 2).add(fibonacci(n - 1));
}

The algorithm is built in a recursive way. That means that the fibonacci method calls itself to compute the values.

Fibonacci stream example

The third example uses streams for the calculation.

Main.java
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

List<BigInteger> fibonacci(int limit) {

    var vals = Stream.iterate(new BigInteger[] { BigInteger.ZERO, BigInteger.ONE },
            t -> new BigInteger[] { t[1], t[0].add(t[1]) })
            .limit(limit)
            .map(n -> n[1])
            .collect(Collectors.toList());

    return vals;
}

void main() {

    System.out.println(fibonacci(100));
}

This example calculates the values up to a certain limit.

var vals = Stream.iterate(new BigInteger[] { BigInteger.ZERO, BigInteger.ONE },
        t -> new BigInteger[] { t[1], t[0].add(t[1]) })
        .limit(limit)
        .map(n -> n[1])
        .collect(Collectors.toList());

The Stream.iterate method produces an infinite sequential ordered Stream generated by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.

The function (in the form of t -> new BigInteger[] { t[1], t[0].add(t[1]) } lambda) adds the last two values of the sequence. The limit method truncates the sequence to limit values. The map method picks the next fibonacce value from the array. Finally, we transform the sequence into a list with collect.

Source

Fibonacci sequence

In this article we have shown how to calculate Fibonacci series in Java in three different ways: classic loop, recursive algorithm and functional way.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java tutorials.