Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown cause of exception

Tags:

java

eclipse

Every time I run this, I get an error that reads: "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);
        }
    }
}
like image 524
tlb50 Avatar asked Jan 30 '26 08:01

tlb50


2 Answers

num is a long. When you compare an int with a long like x < num, the int will be promoted to a long. Assuming your num is big enough (bigger than the max value of an int), x will never reach it and your x++ will be executed. At some point, the value of x will overflow and become 0.

like image 173
Sotirios Delimanolis Avatar answered Feb 01 '26 22:02

Sotirios Delimanolis


Since num is a long, if you choose it sufficiently large, x, which is only an int, will overflow. And when it does that, as an int it will be zero. And then you get zero-divide in the remainder operation.

like image 39
Andrew Lazarus Avatar answered Feb 01 '26 23:02

Andrew Lazarus