Fibonacci int []序列

时间:2013-05-27 21:46:35

标签: java fibonacci

无论我做什么,我都无法做到这一点。

返回一个大小为len的int [],它具有第一个len斐波纳契数。例如:n = 6,返回{1,1,2,3,5,8}。 (前提:n> = 2)

fibonacci(3) → {1, 1, 2}
fibonacci(6) → {1, 1, 2, 3, 5, 8}
fibonacci(8) → {1, 1, 2, 3, 5, 8, 13, 21}

这是我做的事情

if (n == 0) {
    return 0;
else if (n == 1)
    return 1;
else
    return fibonnaci(n - 1) + fibonnaci(n - 2);

3 个答案:

答案 0 :(得分:1)

public static int[] FibLength(int l)
{
    int fib[] = new int[l];
    fib[0] = 1;
    fib[1] = 1;

    for (int i=2; i<fib.length; i++)
        fib[i] = fib[i-1] + fib[i-2];

    return fib;
}

答案 1 :(得分:1)

迭代版本:

public int[] sonOfBonacci(int n) {
    int[] result = new int[n];
    result[0] = 1;
    if (n > 1) {
        result[1] = 1;
        for (int j = 1; j < n - 1; j++) {
            result[j + 1] = result[j - 1] + result[j];
        }
    }
    return result;
}

答案 2 :(得分:0)

使用大数字:

public static void main(String[] args) {

    // Precalculate enough fibs
    List<BigInteger> list = new ArrayList<BigInteger>();
    list.add(BigInteger.ONE);
    list.add(BigInteger.ONE);
    for (int i = 2; i < 512; i++) {
        list.add(list.get(i - 2).add(list.get(i - 1)));
    }

    // Print first 10
    for (int n = 2; n <= 10; n++) {
        System.out.printf("fibonacci(%d)\t→\t%s%n", n, list.subList(0, n));
    }

}

输出:

fibonacci(2)    →   [1, 1]
fibonacci(3)    →   [1, 1, 2]
fibonacci(4)    →   [1, 1, 2, 3]
fibonacci(5)    →   [1, 1, 2, 3, 5]
fibonacci(6)    →   [1, 1, 2, 3, 5, 8]
fibonacci(7)    →   [1, 1, 2, 3, 5, 8, 13]
fibonacci(8)    →   [1, 1, 2, 3, 5, 8, 13, 21]
fibonacci(9)    →   [1, 1, 2, 3, 5, 8, 13, 21, 34]
fibonacci(10)   →   [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]