Java 中的遞迴斐波那契演算法


斐波那契數列是一種數列,其中的每個數字都是前兩個數字之和。可以使用遞迴方法獲取斐波那契數列中某特定位置的數字。

演示該方法的程式如下

示例

 線上演示

public class Demo {
   public static long fib(long n) {
      if ((n == 0) || (n == 1))
         return n;
      else
         return fib(n - 1) + fib(n - 2);
   }
   public static void main(String[] args) {
      System.out.println("The 0th fibonacci number is: " + fib(0));
      System.out.println("The 7th fibonacci number is: " + fib(7));
      System.out.println("The 12th fibonacci number is: " + fib(12));
   }
}

輸出

The 0th fibonacci number is: 0
The 7th fibonacci number is: 13
The 12th fibonacci number is: 144

接著讓我們來理解一下上面的程式。

fib() 方法計算第 n 個位置的斐波那契數。如果 n 等於 0 或 1,它將返回 n。否則,它將遞迴呼叫自身並返回 fib(n - 1) + fib(n - 2)。展示該方法的程式碼片段如下所示

public static long fib(long n) {
   if ((n == 0) || (n == 1))
      return n;
   else
      return fib(n - 1) + fib(n - 2);
}

在 main() 中,對 fib() 方法使用不同的值進行呼叫。展示該方法的程式碼片段如下所示

public static void main(String[] args) {
   System.out.println("The 0th fibonacci number is: " + fib(0));
   System.out.println("The 7th fibonacci number is: " + fib(7));
   System.out.println("The 12th fibonacci number is: " + fib(12));
}

更新於: 2019 年 7 月 30 日

10K+ 瀏覽量

開啟您的 職業生涯

完成課程獲得認證

馬上開始
廣告