斐波那契數列用JAVA實現
阿新 • • 發佈:2018-11-24
import java.util.Scanner; public class Test { public static void main(String[] args) { int r = test(7); int rs = test2(7); System.out.println("==="+r+"========"+rs); } public static int test(int n){//遞迴的方式 // 1 1 2 3 5 8 13 21 34 55 89 // 該演算法利用遞迴的方式計算第幾項的值 if(n==1 || n==2){ return 1; } return test(n-1) + test(n-2); } public static int test2(int n){//非遞迴的方式 int first = 1; int second = 1; int result = 0 ; //result用來記錄結果,first用來記錄計算項的前面的前面的數,second用來記錄當前計算項的前一項 if(n==1 || n==2){ return 1; } for (int i = 1; i < n - 1; i++) { result = first + second; first = second; second =result; } return result; } }