Java-斐波那契数

时间:2023-03-09 04:03:02
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

Java-斐波那契数

3.代码:

 public class Test {

     //The Fibonacci Sequence is the series of numbers:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
public long fab(int index){ if(index==1 || index==2){
return index-1;
} long f1 = 0L;
long f2 = 1L;
long f3 = 0; for(int i=2 ;i < index ;i++ ){
f3 = f2+f1;
f1 = f2;
f2 = f3;
}
return f3;
} @org.junit.Test
public void test(){
System.out.println(fab(8));
}
}