2

我有递归斐波那契数列的以下代码

    if (term < 2){
        System.out.print("1 ");
        return 1;
    } 
        int results = fibonacci(term - 1) + fibonacci(term - 2);
        System.out.print(results + " ");

        return results;

我得到的输出是

您希望对斐波那契数列执行什么操作:4

1 1 2 1 3 1 1 2 5 第 4 个是 5

我怎么做才能打印

1 1 2 3 第 4 个是 5

4

3 回答 3

1

使用尾递归。

  public static void main(String[] args) {

    System.out.print("The 10th is: " + fibonnaci(10));
  }

  public static int fibonnaci(int number) {
     return fibonnaciHelper(number, 1, 1);
  }

  public static int fibonnaciHelper(int term, int lower, int higher) {
      if (term < 2){
          return higher;

      } 

      System.out.print(higher + " ");
      int results = fibonnaciHelper(term - 1, higher, higher + lower);
      return results;
  }
于 2013-04-24T21:26:10.973 回答
0

您可以尝试以下方法:

public void fib(int n){
    if(n==0)
        System.out.println(1);

    else System.out.println(fib(1,n,0,1);
}

private int fib(int iteration, int limit, int n0, int n1){
    if(iteration==limit)
         return(n0+n1);

    fib(++iteration,limit,n1,(n0+n1));
}
于 2013-05-10T17:13:57.723 回答
0

迭代斐波那契数列 - 它位于某处

public static int fib(int n) {
            int prev1=0, prev2=1;
            for(int i=0; i<n; i++) {
                int savePrev1 = prev1;
                prev1 = prev2;
                prev2 = savePrev1 + prev2;
            }
            return prev1;
}
于 2013-04-24T21:20:12.653 回答