如何将BigInt用于修改过的Fibonacci

时间:2015-12-06 03:44:35

标签: java dynamic-programming biginteger

我正在尝试解决此问题: problem

通过动态编程,我能够解决问题,到目前为止这是代码:

    import java.util.Scanner;
    public class Dy
    {
        static long[] storage = new long[20];
        public static void main(String[] args)
        {
            Scanner sx = new Scanner(System.in);

            storage[0] = sx.nextInt();
            storage[1] = sx.nextInt();
            int x = sx.nextInt();

            System.out.println(beast(x-1));


        }

    public static long beast(int n)
    {
        if(n==0)
            return storage[n];
        if(n==1)
            return storage[n];

        if(storage[n]!=0)
            return storage[n];

        storage[n] = (beast(n-1)*beast(n-1)) + beast(n-2);

        return storage[n];
    }
}

真正的麻烦在这里,如果n大约是20,那么即使long数据类型也不会保留该值,因此选择显然是BigInteger,但作为一个学习者,我想知道如何在Java中使用BigInteger和数组?任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:1)

你可以使用Map<Integer, BigInteger>之类的东西,

static Map<Integer, BigInteger> storage = new HashMap<>();

public static void main(String[] args) {
    Scanner sx = new Scanner(System.in);

    // Add 0 and 1.
    storage.put(0, BigInteger.valueOf(sx.nextInt()));
    storage.put(1, BigInteger.valueOf(sx.nextInt()));
    int x = sx.nextInt();

    System.out.println(beast(x - 1));
}

public static BigInteger beast(int n) {
    if (!storage.containsKey(n)) {
        BigInteger t = beast(n - 1);
        storage.put(n, t.multiply(t).add(beast(n - 2)));
    }
    return storage.get(n);
}