斐波那契算法的java實現

斐波那契(Fobonacci)數列的第1和第2個數分別爲1和1,從第三個數開始,每個數等於

其前兩個數之和(1,1,2,3,5……)

實現1:
public static Integer fobonacci(Integer n){
   if(n<0||n==0){
      System.out.println("參數必須大於0");
      return 0;
   }
   if(n==1||n==2){
      return 1;
   }
   Integer first = 1;
   Integer second = 1;
   Integer result = 0;
   for(int i=3;i<=n;i++){
      result = first+second;
      first = second;
      second = result;
   }
   System.out.println("n=="+n+":result="+result);
   return result;

}
實現2:
public static Integer fobonacci(int n) {
   if (n == 0) {
      return 0;
   } else if (n == 1) {
      return 1;
   }
   return fobonacci(n - 1) + fobonacci(n - 2);
}

變種1:輸出前20個數,每6個數一行
public static Integer fobonacci(Integer n){
   if(n<0||n==0){
      System.out.println("參數必須大於3");
      return 0;
   }
   if(n==1||n==2){
      return 1;
   }
   Integer first = 1;
   Integer second = 1;
   Integer result = 0;
   System.out.print(first+","+second+",");
   for(int i=3;i<=n;i++){
      result = first+second;
      System.out.print(result+",");
      if(i%6==0){
         System.out.println("");
      }
      first = second;
      second = result;
   }
   System.out.println("\nn=="+n+":result="+result);
   return result;

}

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