Java 實(shí)例 - 斐波那契數(shù)列
斐波那契數(shù)列指的是這樣一個(gè)數(shù)列 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項(xiàng)是0,第1項(xiàng)是第一個(gè)1。
這個(gè)數(shù)列從第三項(xiàng)開始,每一項(xiàng)都等于前兩項(xiàng)之和。
以下實(shí)例演示了 Java 斐波那契數(shù)列的實(shí)現(xiàn):
/* author by w3cschool.cn 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)); } } }
以上代碼運(yùn)行輸出結(jié)果為:
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
更多建議: