斐波那契數列指的是這樣一個數列0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584, 4181,6765,10946,17711,28657,46368……
特別指出:第0項是0,第1項是第一個1。
這個數字從第三項開始,每一項都等於前兩項之和。
以下實例示範了 Java 斐波那契數列的實作:
/* author by w3cschool.cc MainClass.java */public class MainClass { public static long fibonacci(long number) { if ((number == 0) || (number == 1)) return number; else return fibonacci(number - 1) + fibonacci(number - 2); } public static void main(String[] args) { for (int counter = 0; counter <= 10; counter++){ System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter)); } }}
以上程式碼運行輸出結果為:
Fibonacci of 0 is: 0 Fibonacci of 1 is: 1 Fibonacci of 2 is: 1 Fibonacci of 3 is: 2 Fibonacci of 4 is: 3 Fibonacci of 5 is: 5 Fibonacci of 6 is: 8 Fibonacci of 7 is: 13 Fibonacci of 8 is: 21 Fibonacci of 9 is: 34 Fibonacci of 10 is: 55
以上就是Java 實例- 斐波那契數列的內容,更多相關內容請關注PHP網網路(m.sbmmt.com)!