1

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.

plethora
  • 135
  • 1
  • 8
  • Many conditions besides divide-by-zero can trigger an ArithmeticException. An operation that results in an imaginary number, for instance, or an integer overflow. If you're sure it's not a div0, chances are it's an overflow. – Michael Petrotta Jun 05 '13 at 03:30
  • may be you got `0` when insert value from s.nextInt() – Ahmad Azwar Anas Jun 05 '13 at 03:30
  • Don't you get ahy other information form the exception?? – Thihara Jun 05 '13 at 03:32
  • Overflow? You have a divisor of `j` squared, which could possibly result in zero value. – xiaofeng.li Jun 05 '13 at 03:41
  • They don't show the test cases, but I believe that they don't insert 0, because it is supposed to be a length measure. And there's no other information, that's all it says. – plethora Jun 05 '13 at 03:42
  • it's an overflow problem i think when u put b*j it's possibly to overflow the range of integer. i test this 1 123123123 123123123 Exception in thread "main" java.lang.ArithmeticException: / by zero at test.Test.main(Test.java:15) – nachokk Jun 05 '13 at 03:54

2 Answers2

1

You are seeing an overflow. Try the following input, and you can get the ArithmeticException.

1
256 256
xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30
0

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!");
    }
}
jerry
  • 2,581
  • 1
  • 21
  • 32