代碼如下:
代碼如下:
public class Fibonacci {
public static long recursive(int n) {
if (n <= 0)
return 0;
if (n == 1)
return 1;
return recursive(n - 1) + recursive(n - 2);
}
public static long loop(int n) {
if (n <= 0)
return 0;
if (n == 1)
return 1;
long fib1 = 0;
long fib2 = 1;
long sum = 0;
for (int i = 2; i <= n; i++) {
sum = fib1 + fib2;
fib1 = fib2;
fib2 = sum;
}
return sum;
}
}
用遞歸的方式的效率遠遠不如循環!