斐波那契数列

 1 package com.yan.offer;
 2 
 3 /**
 4  * 大家都知道斐波那契数列(0、1、1、2、3、5、8、13、21、34 ...),F(n)=F(n-1)+F(n-2),
 5  * 现在要求输入一个整数n,请你输出斐波那契数列的第n项。
 6  * 
 7  * @author Yan
 8  *
 9  */
10 public class Fibonacci {
11 
12     public Fibonacci() {
13     }
14 
15     public static void main(String[] args) {
16         Fibonacci fibonacci = new Fibonacci();
17         System.out.println(fibonacci.findNth2(0));
18     }
19 
20     /*
21      * recursive implementation, however the cost is too expensive.
22      */
23     public int findNth(int n) {
24 
25         if (n < 0)
26             return -1;
27         if (n == 0)
28             return 0;
29         if (n == 1) {
30             return 1;
31         }
32         return findNth(n - 1) + findNth(n - 2);
33 
34     }
35 
36     /**
37      * An implementation without recurse. It is faster than the recursive
38      * implementation.
39      * 
40      * @param n
41      * @return
42      */
43     public int findNth2(int n) {
44         if (n < 0)
45             return -1;
46         if (n == 0)
47             return 0;
48         if (n == 1)
49             return 1;
50         if (n >= 2) {
51             /*
52              * declare two point (not very exactly) to record F(n-2) and F(n-1)
53              * and move step by step.
54              */
55             int temp1 = 0;
56             int temp2 = 1;
57             int result = temp1 + temp2;
58             for (int i = 2; i <= n; i++) {
59                 result = temp1 + temp2;
60                 temp1 = temp2;
61                 temp2 = result;
62             }
63             return result;
64         }
65         return -1;
66     }
67 
68 }

 

posted on 2016-06-05 10:59  Yanspecial  阅读(214)  评论(0编辑  收藏  举报