斐波那契数列,用 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;

        }


    }

}


MM们
浏览 151回答 2
2回答

ITMISS

使用流 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)....iterate 需要一个 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&nbsp;long[]{0,&nbsp;1},&nbsp;t&nbsp;->&nbsp;new&nbsp;long[]{t[1],&nbsp;t[0]&nbsp;+&nbsp;t[1]}) &nbsp;&nbsp;&nbsp;&nbsp;.limit(10) &nbsp;&nbsp;&nbsp;&nbsp;.map(t&nbsp;->&nbsp;t[0]) &nbsp;&nbsp;&nbsp;&nbsp;.forEach(System.out::println);这是流 api:https ://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

Qyouu

这是一个递归的“单行代码”(函数体只有一行使用嵌套三元):public static long Fibonacci(int termNumber){&nbsp; &nbsp; return (termNumber == 1) ? 0 : (termNumber == 2) ? 1 : Fibonacci(termNumber - 1) + Fibonacci(termNumber -2);}示例驱动程序:public class Fibonacci{&nbsp; &nbsp; public static void main(String[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 1; i <= 10; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Fibonacci(" + i + ") = " + Fibonacci(i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static long Fibonacci(int termNumber)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return (termNumber == 1) ? 0 : (termNumber == 2) ? 1 : Fibonacci(termNumber - 1) + Fibonacci(termNumber -2);&nbsp; &nbsp; }}输出:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java