Unknown reason for exception

Every time I run this I get an error: "Exception in thread" main "java.lang.ArithmeticException: / by zero". I'm not sure why this isn't working.

public static void Solve(long num){
    for(int x = 1; x < num; x++){
        if((num % x) == 0){    //error occurs here
            System.out.println(x);
        }
    }
}

      

+3


source to share


2 answers


num

is long

. When you compare int

with long

how x < num

, int

will advance to long

. Assuming yours num

is large enough (greater than the maximum value int

), x

will never reach it and yours x++

will be executed. At some point, the value will x

overflow and become 0

.



+9


source


Since num is long, if you choose it large enough, x, which is only an int, will overflow. And when it does it like int will be zero. And then you get a zero division in the break operation.



+3


source







All Articles