Search code examples
javamultiplication

Why changing the data type changing the whole result?


I wrote a program to calculate the multiplication of odd numbers between 1 and 100. So why does changing the data type give me a whole different output? Why is the output a negative number when I use int? Additionally, the other results seem weird. Code:

long total = 1L;
for (int i = 1; i <= 100; i++) {
    if (i % 2 != 0) {
        total *= i;
    }
}
System.out.println(total);

The output in different cases :

5196472710489536419 (if total is long)

-373459037 (if total is int)

2.7253921397507295E78 (if total is double)

Infinity (if total is float)


Solution

  • With different datatypes, the result would overflow in different ways. The result when using a double looks correct, although you're probably losing a lot of precision there. If you want to properly multiply an integer of arbitrary size, you should probably use a BigInteger:

    BigInteger total = BigInteger.ONE;
    for (int i = 1; i <= 100; i++) {
        if (i % 2 != 0) {
            total = total.multiply(BigInteger.valueOf(i));
        }
    }
    System.out.println(total);
    

    Side note: instead of iterating all the ints between 1 and 100 and checking if they are odd or not, you could start with 1 and then increment each iteration by 2 instead of 1:

    BigInteger total = BigInteger.ONE;
    for (int i = 1; i < 100; i+=2) {
        total = total.multiply(BigInteger.valueOf(i));
    }
    System.out.println(total);