You've got an overflow because 3 * n + 1
became larger than Integer.MAX_VALUE
. So n
gets negative and the while loop will never halt.
Use long
instead of int
for n
!
If you want to check for the overflow instead:
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
if (n > (Integer.MAX_VALUE - 1) / 3) {
throw new RuntimeException("overflow!");
}
n = 3 * n + 1;
}
counter++;
}
Addition for Java 8
Since Java 8, the Math
class provides additional static methods for 'exact' arithmetics (addition, subtraction, multiplication, division) that throw an ArithmeticException
in case of an overflow. Using these methods, the code can be simplified:
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = Math.addExact(Math.multiplyExact(3, n), 1);
}
counter++;
}