1. 程式人生 > >fibonacci數列的遞迴與非遞迴實現

fibonacci數列的遞迴與非遞迴實現

fibonacci數列的遞迴與非遞迴實現

public class fibonacci {
      public static void main(String arg[]){
//    	fib1();
    	System.out.println(fib2(4));
      }
      static void fib1(){
    	  int i;
    	  int [] a=new int [40];
    	  a[0]=1;
    	  a[1]=1;
    	  System.out.print(a[0]+" "+a[1]+" ");
    	  for(i=2;i<40;i++){
    		  a[i]=a[i-1]+a[i-2];
    		  System.out.print(a[i]+" ");
    	  }
      }
      static int  fib2(int i){
    	  
    	  if (i<2)
    		  return i==0?0:1;
    	  return fib2(i-1)+fib2(i-2);
      }
}