Java实现斐波那契数列的四种算法

public class Fibonacci {
   public static int fibo1(int n){ //递归算法
   if(n==1||n==2){
   return 1;
   }
   else{
   return fibo1(n-1)+fibo1(n-2);
   }
   }
  
   public static int fibo2(int n){ //数学表达式算法Fib(n) = [(1+√5)/2]^n /√5 - [(1-√5)/2]^n /√5
   return (int) ((Math.pow((1+Math.sqrt(5.0))/2,n)-Math.pow((1-Math.sqrt(5.0))/2,n))/Math.sqrt(5.0));
   }
  
   public static int fibo3(int n){ //循环函数算法
   int a=1,b=1,c=0;
   for(int i=2;i   c=a+b;
   a=b;
   b=c; 
   }
   return c;
   }
   public static int fibo4(int n){//循环向量函数算法
   int fi=0;
   int[] fib = new int[n]; 
   fib[0] = 1; 
   fib[1] = 1; 
   for(int i = 2; i < fib.length; i++){
   
   fib[i] = fib[i-1] + fib[i-2];
   fi=fib[i];
   }
   return fi;
   }
   public static void main(String[] args) {
   System.out.println(fibo1(10));
   System.out.println(fibo2(10));
   System.out.println(fibo3(10));
   System.out.println(fibo4(10));
   }
  
  }

点赞