zoukankan      html  css  js  c++  java
  • Java-斐波那契数

    1.目标:使用非递归求斐波那契,0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

    2.思路:观察规律得:从第3个数起,把和从为下一个数的加数,把加数作为下一个数的被加数,即三个数f1,f2,f3循环执行f3=f2+f1,f1=f2,f2=f3......

    第3个数1=1+0

    第4个数2=1+1

    第5个数3=2+1

    第6个数5=3+2

    3.代码:

     1 public class Test {
     2     
     3     //The Fibonacci Sequence is the series of numbers:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
     4     public long fab(int index){
     5         
     6         if(index==1 || index==2){
     7             return index-1;
     8         }
     9         
    10         long f1 = 0L;
    11         long f2 = 1L;
    12         long f3 = 0;
    13         
    14         for(int i=2 ;i < index ;i++ ){
    15             f3 = f2+f1;
    16             f1 = f2;
    17             f2 = f3;
    18         }
    19         return f3;
    20     }
    21 
    22     @org.junit.Test
    23     public void test(){
    24         System.out.println(fab(8));
    25     }
    26 }
  • 相关阅读:
    23.课程应用接口
    22.课程页面设计
    21.手机接口
    20.云通讯
    19.JWT
    18.权限认证
    解决github下载慢的终极方法
    vs code 配置c/c++环境
    Python 字符编码处理总结
    Python编码
  • 原文地址:https://www.cnblogs.com/shamgod/p/4601000.html
Copyright © 2011-2022 走看看