Java語言非遞迴求第n個斐波那契數

fly豬豬7發表於2020-09-25

非遞迴方法:

public static int fib(int n) {
        if (n <= 0) return -1;
        if (n == 1) return 0;
        if (n == 2) return 1;
        int first = 0;
        int second = 1;
        int temp;
        for (int i = 1; i < n - 1; i++) {
            temp = second;
            second = second + first;
            first = temp;
        }
        return second;
    }

遞迴:

public static int fib(int n) {
        if (n <= 0) return -1;
        if (n == 1) return 0;
        if (n == 2) return 1;
        return fib(n - 1) + fib(n - 2);
    }

相關文章