编程练习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)

转载于:https://www.cnblogs.com/qyddbear/archive/2012/04/05/2433692.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值