Fibonacci sequence for n > 46 Java

后端 未结 4 1949
旧时难觅i
旧时难觅i 2021-01-23 22:38

I have the following code which provides the correct values for n < 47.

public static int fib(int n) {
    int nthTerm = 0;
    if (n == 2)
        nthTerm =          


        
4条回答
  •  执念已碎
    2021-01-23 23:25

    The reason you can't use int is because fib(47) is 2971215073 which overflows Java's signed 32-bit int (231-1). You could use a memoization optimization to implement it with BigInteger like,

    private static Map memo = new HashMap<>();
    static {
        memo.put(0, BigInteger.ZERO);
        memo.put(1, BigInteger.ONE);
    }
    
    public static BigInteger fib(int n) {
        if (memo.containsKey(n)) {
            return memo.get(n);
        }
        BigInteger v = fib(n - 2).add(fib(n - 1));
        memo.put(n, v);
        return v;
    }
    

提交回复
热议问题