斐波纳契数为负数

我使用动态编程技术编写了以下代码,但当我对数字220运行Fibonacci时得到一个负数。此程序中是否有错误?

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Fibonaci {

    public static void main(String[] args) {
        System.out.println(" number ");
        long startTime = System.currentTimeMillis();
        HashMap<Integer, Integer> memoized = new HashMap<Integer, Integer>();
        int fib = fibonanci(220, memoized);
        System.out.println(" Total Time "
                + (System.currentTimeMillis() - startTime));

    }

    private static int fibonanci(int n, HashMap<Integer, Integer> memoized) {
        System.out.println(" n " + n);
        if (memoized.containsKey(n)) {
            return memoized.get(n);
        }

        if (n <= 0) {
            return 0;
        }
        if (n <= 2) {
            return 1;
        } else {
            int febonani = fibonanci(n - 1, memoized)
                    + fibonanci(n - 2, memoized);
            System.out.println(" febonani " + febonani);
            if (!memoized.containsKey(n)) {
                memoized.put(n, febonani);
            }
            return febonani;
        }
    }


}

解决方案

使用BigInteger而不是int/Integer来避免依瓦略指出的精度问题(Java的<[2-1]和Integer不能表示大于231位的无符号整数,long/Long不超过263)。BigIntegersupports arbitrary precision(仅受JVM可用的内存量限制)。

您的代码将如下所示:

 private static BigInteger fib(int n, HashMap<Integer, BigInteger> memoized) {
    System.out.println(" n = " + n);
    if (memoized.containsKey(n)) {
        return memoized.get(n);
    } else if (n <= 0) {
        return BigInteger.ZERO;
    } else if (n <= 2) {
        return BigInteger.ONE;
    } else {
        BigInteger sum = fib(n - 1, memoized).add(fib(n - 2, memoized));
        System.out.println(" fib(" + n + ") = " + sum;
        memoized.put(n, sum);
        return sum;
    }
}  

相关文章