【问题标题】:How to make fibonacci method? [closed]如何制作斐波那契方法? [关闭]
【发布时间】:2015-01-10 14:44:19
【问题描述】:

我想得到斐波那契的值,而不是前一个数字。例如:

public class Fibonacci {

    public static int f(int n){
        if (n <= 1) {
            return n;
        } else {
            return f(n - 1) + f(n - 2);
        }
    }
    public static void main (String args[]) {
        System.out.println(f(4));
    }
}

该方法输出 3。我想获得 4+3 = 7。 我该怎么做?

【问题讨论】:

  • 在 Google 中搜索斐波那契而不是斐波坎尼。该算法被广泛用作递归的示例。 (感谢@BobJarvis 编辑问题)。
  • 7 不是斐波那契数。
  • 7 根本不是斐波那契数,更不用说第四个斐波那契数了。
  • 方法应该怎么做?返回i-th 斐波那契数?
  • @lurker:咖啡。需要……咖啡…………

标签: java algorithm math


【解决方案1】:

Fibonacci sequence 内容如下:

1 1 2 3 5 8 13 21 ...

基本情况是完全错误的:

@Cacheable
public static int f(int n) {
    if (n <= 2) {//base case
        return 1;  //first two numbers are 1
    } else {
        return f(n - 1) + f(n - 2);
    }
}

这给了43

注意:这些不是“数组索引”,而是“人类索引”

但是这种方法实际上效率太低,不实用。您应该使用动态规划或迭代变体来计算。

@Cacheable 是一个spring-directive,它将函数转换为具有内存的函数。换句话说,一旦f(4)被计算出来,它就不会重新计算它,而是从商店中获取。删除 @Cacheable 仍然会给出正确的结果,但对于较大的 n 会花费太多时间。

因此,这会将算法转变为一种有效的动态规划方法。

因此,迭代算法是:

public static int f(int n){
    if (n <= 2) {//base case
        return 1;  //first two numbers are 1
    } else {
        int a = 1;
        int b = 1;
        for(int i = 2; i < n; i++) {
            int t = a+b;
            a = b;
            b = t;
        }
        return b;
    }
}

因为这以线性时间运行,而前一个需要指数时间。

jdoodle.

或者正如@Jarlax 所说,您也可以使用this approachO(log n) 时间内计算。

【讨论】:

  • 还有一个很好的算法,涉及矩阵 [[0, 1], [1, 1]] 幂 -stackoverflow.com/questions/14781543/…
  • @Jarlax:谢谢。它包含在答案中,尽管由于涉及更复杂的数学,描述算法更难。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
  • 1970-01-01
  • 2014-11-09
相关资源
最近更新 更多