斐波那契數列的兩種實現方式(遞迴和迴圈)
阿新 • • 發佈:2018-12-11
public class Fibonacci { public static long F(int N){ int f0 = 0; int f1 = 1; int fn = 0; if(N == 0) return f0; if(N == 1) return f1; for(int i = 1; i < N; i++){ fn = f0 + f1; f0 = f1; f1 = fn; } return fn; } public static long RecursionF(int N){ if(N == 0) return 0; if(N == 1) return 1; return RecursionF(N - 1) + RecursionF(N - 2); } public static void main(String[] args) { // TODO Auto-generated method stub int N = 4; System.out.println(F(N)); System.out.println(RecursionF(N)); } }
當要求的數值變大時,遞迴的方法就會顯得很慢,沒有迴圈那麼快速。