Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?

Tags:

java

math

puzzle

why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?

like image 316
Satish Avatar asked Aug 19 '09 17:08

Satish


1 Answers

Because the multiplication overflows 32 bit integers. In 64 bits it's okay:

public class Test
{
    public static void main(String[] args)
    {
        int intProduct = 24 * 60 * 60 * 1000 * 1000;
        long longProduct = 24L * 60 * 60 * 1000 * 1000;
        System.out.println(intProduct); // Prints 500654080
        System.out.println(longProduct); // Prints 86400000000
   }
}

Obviously after the multiplication has overflowed, the division isn't going to "undo" that overflow.

like image 86
Jon Skeet Avatar answered Sep 19 '22 18:09

Jon Skeet