Search code examples
javaif-statementdivide-by-zeroarithmeticexception

Why is it implying I'm dividing by zero?


I'm solving a few exercises from HackerRank.com and the code works perfectly on Netbeans and even in the page compiler for test cases, but when I submit the code it throws me this error in every test(except the last):

ArithmeticException: thrown at Solution.main(Solution.java:15)

Here's the code:

     Scanner s = new Scanner(System.in);
     int a = s.nextInt(),j=1;
     for(int i=0; i<a; i++){
         int b = s.nextInt(), c =s.nextInt();
         for(j = b*c; j>0;j--) {
         if((b*c)%(j*j)==0){
             System.out.println(b*c/(j*j));
             break;}
         } 
     }

Line 15 is:

    if((b*c)%(j*j)==0){

What's wrong with the statement? I've set 'j' to be different from 0 in the for loop, so no reason for dividing by zero, which was the only explanation I could find by myself.

Thank you in advance.


Solution

  • If b*c is large, j will eventually equal 2147418112 65536 (=216) and j*j will be 0 (remember, Java ints are always 32-bits). Performing % when the divisor is 0 results in your ArithmeticException. Note that any multiple of 65536 will cause this error. The 2147418112 (=231-216) originally referenced above is just the largest multiple that will fit in an int.

    Example code (you can run it yourself at http://ideone.com/iiKloY):

    public class Main
    { 
         public static void main(String []args)
         {
            // show that all multiples of 65536 yeild 0 when squared
            for(int j = Integer.MIN_VALUE; j <= Integer.MAX_VALUE - 65536; j += 65536)
            {
                if((j*j) != 0)
                {
                    System.out.println(j + "^2 != 0");
                }
            }
            System.out.println("Done!");
        }
    }