4
public class Main {

    public static void main(String[] args) {

        long product = 1L;
        product = (9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);
        System.out.println(product);
        product = 9L;
        for (int i = 0; i != 12; i++) {
            product *= 9;
        }
        System.out.println(product);

    }
}

Output :-754810903
2541865828329 //this one is correct

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
Prince
  • 45
  • 4
  • 7
    `(9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9)` is evaluated as an int and thus overflow. Try with `(9L * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9)` – Alexis C. May 25 '14 at 11:12
  • 1
    This is a very similar problem to `double result=9/10;` which equals 0. Casting to the variable type is the last thing that happens – Richard Tingle May 25 '14 at 11:15

2 Answers2

7

In your first attempt, you don't make sure the result is long. Therefore - it overflows as int.

product = (9L * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
7

That is because int data type is not enough to take all much that value.

Convert it to long.

product = (9L * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);

Or atleast cast it first. But make sure you get a long data type value. Otherwise it won't work and you'll never get that result. That you wanted :)

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103