Java如何使用方法來計算斐波納契系列?

2019-10-16 22:30:18

在Java中,如何使用方法來計算斐波納契系列?

這個例子顯示了如何使用方法來計算斐波納契系列的數位。

package com.yiibai;

public class CalculatingFibonacciSeries {
    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

範例-2

以下是解決漢諾塔的另一個例子

package com.yiibai;

public class CalculatingFibonacciSeries2 {
    public static void main(String a[]) {
        int count = 15;
        int[] feb = new int[count];
        feb[0] = 0;
        feb[1] = 1;

        for (int i = 2; i < count; i++) {
            feb[i] = feb[i - 1] + feb[i - 2];
        }
        for (int i = 0; i < count; i++) {
            System.out.print(feb[i] + " ");
        }
    }
}

執行上面範例程式碼,得到以下結果 -

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377