I’m trying to make my Hailstone sequence output the smallest integer that cannot be computed due to the restrictions on int, but for some reason it still is not working. Any ideas as to why it’s not would be greatly appreciated.
public static void main(String[] args) {
int x=2;
int count = x;
//Collatz Conjecture computation
while (true)
{ x=2;
x =count;
while (x != 1)
{
if (x % 2 == 0)
x = x / 2;
if (x % 2 == 1)
x = x * 3 + 1;
if (x < 0)
{ System.out.print("The integer " + count + " cannot have its Hailstone sequence computed using int variables. ");
return;
}
}
count ++;
}
}
Currently, your
Hailstone sequencewill reach an unending sequence of4, 2, 1, 4, 2, 1, ..., because, you are having multipleif'sinstead ofif-else.You should change your set of
if'sto: –So, what was the Issue?
If you were using just
if's, then at one point of time, yourxwill become1due to firstifcondition.So, with
x = 1, the 2ndifwould be executed, andxwould now become –1 * 3 + 1=4. Then the while loop continues. Again,xbecomes2(1stif), then againwhileloop continues (As2nd ifis not satisfied now.2 % 2 != 1), and thenxbecomes1(1stif), then4(2ndif), and so on. This problem arise, because both yourifblocks was getting executed everytime.Just to complete the answer, I think you don’t even need that last condition –
x < 0. Your while loop will automatically break whenx becomes 1. And this must be the only condition of ending the sequence. Because, once you start with value1, you would end up in that deadly sequence. So, just removeif (x < 0)part. Not Needed.So, you should just use: –
in your
innerwhile.