0

I am trying to solve a problem where I need to return the index value of given number in Fibonacci series. I wrote same code in Java and Python, but both are returning different values. Why?

Java code:

import java.util.HashMap;
public class Fibonacci
{
   static int fib (int n, HashMap<Integer, Integer> memo)
   {
      for(int i: memo.keySet())
         if(i==n)
            return memo.get(i);
      if(n <= 2 )   return 1;
      memo.put(n, fib(n-1, memo) + fib(n-2, memo));
      return memo.get(n);    
   }
   public static void main(String[] args) 
   {
      System.out.println(fib(50, new HashMap<>()));
   }
}
input: 50

output: -298632863

Python code:

def fib(n, memo):
       if(n in memo):
           return memo[n]
       if(n <= 2 ):
           return 1
       memo[n] = fib(n-1, memo) + fib(n-2, memo)
       return memo[n];
    print( fib( 50, { } )
input: 50
output: 12586269025
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

3

You have an integer overflow in Java because you use 32-bit int - you need to use at least 64 bit integers (long or BigInteger) to store 12586269025.

According to (Source: Oracle primitive datatypes) the highest value for normal int is

a 32-bit signed two's complement integer, which has a minimum value of -2^31 and a maximum value of (2^31)-1

which calculates to

 2^31-1 =  2147483647
fib(50) = 12586269025   # too big to fit

Python integers can hold arbitarily big numbers, so it is no problem there.

See The range of int in Java

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 2
    For 64-bit you use `long`, if you need even more than that, then you use `BigInteger`. And the site you link does not show that `int` is the highest value for normal integers, that would be a `long` (_"a 64-bit two's complement integer"_). – Mark Rotteveel Aug 22 '21 at 08:27
  • @Mark I stand corrected :) – Patrick Artner Aug 22 '21 at 08:31