I was doing an exercise and wrote the following code:
while (n != 1) {
if (n % 2 == 0) n = n / 2;
if (n % 2 == 1) n = 3 * n + 1;
++count;
}
But it caused the loop to run infinitely. The trick was to remove the second if and put an else statement instead of the second if.
I cannot see why this would make any difference for my example. n is continuously decreasing down to 1, and both if-statements shouldn't be able to execute at the same time during one loop iteration.
Obviously, the if-else version logically makes more sense, since if the number isn't even, then it has to be odd. But I don't see what edge case I am missing with two ifs.
Aucun commentaire:
Enregistrer un commentaire