Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci numbers, with an one-liner in Java? [duplicate]

Tags:

java

I would like to know how can I find nth fibonacci number with most Javatic way with a one-line. This is my code, but i want to learn better way.

class FibonacciExample1 {
    public static void main(String[] args) {
        int n1 = 0, n2 = 1, n3, i, count = 10;
        System.out.print(n1 + " " + n2);//printing 0 and 1    

        for (i = 2; i < count; ++i)//loop starts from 2 because 0 and 1 are already printed    
        {
            n3 = n1 + n2;
            System.out.print(" " + n3);
            n1 = n2;
            n2 = n3;
        }

    }
}
like image 268
Alian Drovez Avatar asked Dec 11 '22 02:12

Alian Drovez


1 Answers

With stream api this is very easy

Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.... The first two numbers of the series are 0 and 1, and each subsequent number is the sum of the previous two. The series of Fibonacci tuples is similar; you have a sequence of a number and its successor in the series: (0, 1), (1, 1), (1, 2), (2, 3), (3, 5), (5, 8), (8, 13), (13, 21)....

iterate needs a lambda to specify the successor element. In the case of the tuple (3, 5) the successor is (5, 3+5) = (5, 8). The next one is (8, 5+8). Can you see the pattern? Given a tuple, the successor is (t[1], t[0] + t[1]). This is what the following lambda specifies: t -> new int[]{t[1],t[0] + t[1]}. By running this code you’ll get the series (0, 1), (1, 1), (1, 2), (2, 3), (3, 5), (5, 8), (8, 13), (13, 21).... Note that if you just wanted to print the normal Fibonacci series, you could use a map to extract only the first element of each tuple:

Stream.iterate(new long[]{0, 1}, t -> new long[]{t[1], t[0] + t[1]})
    .limit(10)
    .map(t -> t[0])
    .forEach(System.out::println);

this is the stream api : https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

like image 183
Melih Altıntaş Avatar answered Jan 18 '23 07:01

Melih Altıntaş