Consider the first iteration :
if ((j % i) == 0 && i != 0) {
&&
and ||
will always evaluate the left operand first, and the condition will short circuit if the condition turns false.
This means that when i != 0
, it will evaluate j % i
first, and so divide by zero. Note that division by zero is undefined behavior.
You need to replace that line by :
if (i != 0 && (j % i) == 0) {
This way, when i == 0
, (j % i) == 0
will not be evaluated
But instead of doing this check, can't you just directly avoid this case? You can simply iterate i
from 1
to m
instead so you can also remove the check:
for (i = 1; i < m; i++) {
Edit: Your runtime claiming you encountered a floating point exception is probably wrong and mistook an arithmetic exception as a divide by zero; or it could be due to a compiler optimization. Something along those lines.