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

  • 相关阅读:
    Java中的IO操作和缓冲区
    Java是否还能再辉煌十年?
    Java的字符串操作
    WordCount(Java实现)
    自我介绍+软工5问
    数据库系统第六章【关系数据理论】(B站视频)
    ini 配置文件读取程序(C语言)
    epoll介绍 实例
    Blizzardhash算法oneway hash
    pychartdir模块安装
  • 原文地址:https://www.cnblogs.com/qyddbear/p/2433692.html
Copyright © 2020-2023  润新知