如何制作斐波那契方法?

时间:2015-01-10 14:44:20

标签: java algorithm math

我想得到斐波纳契的价值,而不是之前的数字。例如:

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。 我该怎么办?

1 个答案:

答案 0 :(得分:2)

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

  

注意:这些不是&#34;数组索引&#34; ,而是&#34;人类指数&#34;

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

@Cacheablespring-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 approach O(log n)时间内计算出来。