亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

斐波那契數列,用 Java 寫一行?

斐波那契數列,用 Java 寫一行?

MM們 2022-12-28 10:52:24
我想知道如何用一行代碼以大多數 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;        }    }}
查看完整描述

2 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

使用流 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 long[]{0, 1}, t -> new long[]{t[1], t[0] + t[1]})
    .limit(10)
    .map(t -> t[0])
    .forEach(System.out::println);

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


查看完整回答
反對 回復 2022-12-28
?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

這是一個遞歸的“單行代碼”(函數體只有一行使用嵌套三元):


public static long Fibonacci(int termNumber)

{

    return (termNumber == 1) ? 0 : (termNumber == 2) ? 1 : Fibonacci(termNumber - 1) + Fibonacci(termNumber -2);

}

示例驅動程序:


public class Fibonacci

{

    public static void main(String[] args)

    {

        for(int i = 1; i <= 10; i++)

        {

            System.out.println("Fibonacci(" + i + ") = " + Fibonacci(i));

        }

    }


    public static long Fibonacci(int termNumber)

    {

        return (termNumber == 1) ? 0 : (termNumber == 2) ? 1 : Fibonacci(termNumber - 1) + Fibonacci(termNumber -2);

    }


}

輸出:

http://img1.sycdn.imooc.com//63abafa00001158e03860327.jpg

查看完整回答
反對 回復 2022-12-28
  • 2 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號