【问题标题】:Printing the n-th Fibonacci number using a for-loop使用 for 循环打印第 n 个斐波那契数
【发布时间】:2018-11-15 18:24:38
【问题描述】:

我使用 return 编写了这个程序,但希望程序只使用 run 方法和 for 循环来做完全相同的事情。它应该打印斐波那契数列中的第 n 个数字。

import acm.program.*;


public class TESTfibonacci extends ConsoleProgram {

    public void run() {

        long n = readInt("Enter a number: ");
        println(fibo(n));
    }

        // Prints the n-th Fibonacci number.
        long fibo(long n) {
        if (n == 0) {
            return 0;
        } else if (n <= 2) {
            return 1;
        } else {
            return fibo(n - 2) + fibo(n - 1);
        }
    }
}

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 尝试搜索fibonacci iteration java
  • 您尝试过什么,遇到过什么问题?我假设您已经快速搜索了这个问题的许多解决方案。

标签: java fibonacci


【解决方案1】:

您可以为此使用动态编程。代码取自here

class Fibonacci {
  static int fib(int n) {
    /* Declare an array to store Fibonacci numbers. */
    int f[] = new int[n + 2]; // 1 extra to handle case, n = 0
    int i; 

    /* 0th and 1st number of the series are 0 and 1*/
    f[0] = 0;
    f[1] = 1;

    for (i = 2; i <= n; i++) {
    /* Add the previous 2 numbers in the series 
        and store it */
      f[i] = f[i - 1] + f[i - 2];
    }

    return f[n];
  }

  public static void main(String args[]) {
    int n = 9;
    System.out.println(fib(n));
  }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多