编程练习3

题目:求Fibonacci数列:1,1,2,3,5,8,……第n个数的值(假设n=40)。

思路:Fibonacci数列满足递推公式:F(1)=1,F(2)=1,F(n)=F(n-1) + F(n-2)

解法1:递归

 1 public class Fibonacci {
2 public static void main(String[] args) {
3 System.out.println(f(40));
4 }
5
6 public static int f(int n) {
7 if (n == 1 || n == 2) {
8 return 1;
9 }
10
11 else {
12 return f(n-1) + f(n-2);
13 }
14 }
15 }


解法2:非递归

 1 public class Fibonacci {
2 public static void main(String[] args) {
3 System.out.println(f(40));
4 }
5
6 public static long f(int n) {
7 if (n < 1) {
8 System.out.println("Invalid parameter!");
9 return -1;
10 }
11
12 if (n == 1 || n == 2) {
13 return 1;
14 }
15
16 long f1 = 1L;
17 long f2 = 1L;
18 long f = 0;
19
20 for (int i=0; i<n-2; i++) {
21 f = f1 + f2;
22 f1 = f2;
23 f2 = f;
24 }
25
26 return f;
27 }
28 }

结果:f(40)为102334155

Java中的int范围是从-2^31到2^31-1,即-2147483648到2147483647。解法2加入了健壮性考虑,long可以换为int型。

 

解法3:迭代

 1 public class Fibonacci {
2 public static void main(String[] args) {
3 System.out.println(f(40));
4 }
5
6 public static long f(int n) {
7      long x = 0;
8 long y = 1;
9 for (int j=1; j<n; j++)
10 {
11 y = x + y;
12 x = y - x;
13 }
14
15 return y;
16 }
17 }

时间复杂度O(n)

 

解法4:公式法

时间复杂度O(1)

posted @ 2012-04-05 20:52  水芊芊  阅读(215)  评论(0编辑  收藏  举报