斐波那契數列指的是這樣一個數列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368........java
這個數列從第3項開始,每一項都等於前兩項之和。算法
package com.bug1; public class Main { public static void main(String[] args) { System.out.println("遞歸實現斐波那契數列"); System.out.println(fib(4)); System.out.println("非遞歸實現斐波那契數列"); System.out.println(fib2(4)); } /* * n= 1 2 3 4 5 6 7 * sum= 1 1 2 3 5 8 * * */ //遞歸實現斐波那契數列 public static int fib(int n) { if(n<=2)return 1; return fib(n-1)+fib(n-2); } //非遞歸實現斐波那契數列 public static int fib2(int n) { if(n<=2)return 1; int first=1; int second=1; int sum=0; while(n>2) { sum=first+second; first=second; second=sum; n--; } return second; } }