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 }

 

posted @ 2015-06-25 21:39  shamgod  阅读(421)  评论(0编辑  收藏  举报
haha