斐波那契數列(JAVA實現)

斐波那契數列(Fibonacci sequence),又稱黃金分割數列、因數學家列昂納多·斐波那契(Leonardoda Fibonacci)以兔子繁殖爲例子而引入,故又稱爲“兔子數列”,指的是這樣一個數列:1、1、2、3、5、8、13、21、34、……在數學上,斐波納契數列以如下被以遞推的方法定義:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3,n∈N*)在現代物理、準晶體結構、化學等領域,斐波納契數列都有直接的應用,爲此,美國數學會從1963年起出版了以《斐波納契數列季刊》爲名的一份數學雜誌,用於專門刊載這方面的研究成果。

核心表達式:F[n]=F[n-1]+F[n-2](n>=3,F[1]=1,F[2]=1)

public class test {
	public static void main(String[] args) {
		int result = test6(12);
		System.out.println(result);
	}
    //遞歸實現方式
    public static int test6(int n) {
		if (n==1 || n==2) {
			return 1;
		}
		return test6(n-1)+test6(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;
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章