Fibonacci

求斐波纳契数列第n个数的两种实现方法。

 1 public class TestFibo {
 2     
 3     public static void main(String[] args){
 4         System.out.println(f(7));
 5         System.out.println(fn(7));
 6     }
 7     
 8     //递归实现
 9     public static  long f(int index){
10         
11         if(index<1){
12             System.out.println("wrong number");
13             return (long)0;
14         }else if(index==1||index==2){
15             return (long)1;
16         }else {
17             return (f(index-1)+f(index-2));
18         }
19     }
20     
21     //非递归实现
22     public static long fn(int index){
23         
24         long f1 = 1l;
25         long f2 = 1l;
26         long f3 = 0l;
27         if(index<1){
28             System.out.println("wrong number");
29             return (long)(-1);
30         }else if(index==1||index==2){
31             return (long)f1;
32         }else{
33             for (int i=0;i<(index-2);i++){
34                 f3 = f1 + f2;
35                 f1 = f2;
36                 f2 = f3;
37             }
38             
39             return f3;
40         }
41     }
42 
43 }
posted @ 2012-08-01 07:55  cnlixl  阅读(137)  评论(0编辑  收藏  举报