斐波那契数字,用Java一线?

Ali*_*vez 3 java

我想知道如何用单行的大多数Javatic方法找到第n个斐波那契数。这是我的代码,但是我想学习更好的方法。

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;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Mel*_*taş 11

使用流API,这非常容易

斐波那契数列:0、1、1、2、3、5、8、13、21、34、55 ....该数列的前两个数字是0和1,每个后续数字是前一个数字的总和二。斐波那契元组的序列相似;您有一个数字序列和该序列的后继序列:(0,1),(1,1),(1,2),(2,3),(3,5),(5,8), (8,13),(13,21)....

迭代需要一个lambda来指定后继元素。在元组(3,5)的情况下,后继是(5,3 + 5)=(5,8)。下一个是(8,5 + 8)。你看到图案了吗?给定一个元组,后继是(t [1],t [0] + t [1])。这是以下lambda指定的内容:t-> new int [] {t [1],t [0] + t [1]}。通过运行此代码,您将获得序列(0,1),(1、1),(1、2),(2、3),(3、5),(5、8),(8、13 ),(13,21)....请注意,如果您只想打印普通的斐波那契数列,则可以使用地图仅提取每个元组的第一个元素:

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);
Run Code Online (Sandbox Code Playgroud)

这是流api:https : //docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html