Search code examples
javadynamic-programmingfibonaccimemoization

Fibonacci number is negative


I have written the following code using dynamic programming technique but I am getting a negative number when I run Fibonacci for number 220. Is there a mistake in this program?

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;
        }
    }


}

Solution

  • Use BigInteger instead of int / Integer to avoid the precision problems pointed out by Ivaylo (Java's int and Integer cannot represent unsigned integers of more than 231 bits, long/Long no more than 263). BigInteger supports arbitrary precision (limited only by the amount of memory available to the JVM).

    Your code would look like:

     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;
        }
    }