java 任何前两个数字的斐波那契

java fibonacci of ANY first two numbers

我需要编写 java 方法来计算用户输入的任何前两个数字的斐波那契数列,假设用户输入 1020,并且想要该系列的前 5 个数字,输出将是 10 20 30 50 80。我已经实现了执行此操作的迭代方法,但我的问题是使用 RECURSIVE 方法来完成它。

public int fRec(int n)
    {
        //base case of recursion
        if ((n == 0) || (n == 1))
            return n;
        else
            //recursive step
            return fRec(n-1) + fRec(n-2);
    }

这是斐波那契数列的典型递归方法,n参数表示用户希望该数列达到多少运行,但我如何修改它以确保该系列使用用户希望系列开始的前两个数字?

要从系列中的特定数字开始,需要为 0 和 1 返回它们:

public int fib(int n, int start1, int start2) {
    switch (n) {
        case 0: return start1;
        case 1: return start2;
        default: return fib(n-1, start1, start2) + fib(n-2, start1, start2);
    }
}

这是计算系列中多个成员的一种非常费力的方法,因为它每次都要回到起点。最好封装在 class:

class Fib {
    private int previous;
    private int current;

    public Fib(int start1, int start2) {
        this.previous = start1;
        this.current = start2;
    }

    public int next() {
        int temp = previous + current;
        previous = current;
        current = successor;
        return current;
    }
}

我会将 memoizationMap<Integer,Long> 一起使用,并将 firstsecond 项传递给 构造函数 。例如,

public class Fibonacci {
    public Fibonacci(long first, long second) {
        memo.put(0, first);
        memo.put(1, second);
    }
    Map<Integer, Long> memo = new HashMap<>();

    public long fRec(int n) {
        if (n < 0) {
            return -1;
        }
        if (memo.containsKey(n)) {
            return memo.get(n);
        }
        long r = fRec(n - 2) + fRec(n - 1);
        memo.put(n, r);
        return r;
    }

    public static void main(String[] args) {
        Fibonacci f = new Fibonacci(10, 20);
        for (int i = 0; i < 5; i++) {
            System.out.println(f.fRec(i));
        }
    }
}

哪些输出(按要求)

10
20
30
50
80

这是计算任意前两个数字的斐波那契数列的另一种方法。

public class Whosebug {

public static void main(String[] args) {

    int first = 10, second = 20;
    System.out.println(first);
    System.out.println(second);
    recursive(first, second, 2);
}

public static void recursive(int first, int second, int count) {
        if (count != 5){
            int temp = first+second;
            first= second;
            second = temp;
            System.out.println(second);
            recursive(first, second, ++count);
        }       
}

}