Reputation: 1612
I'm trying to solve problem 14 on project euler, and my initial brute force attempt has me stumped. For some reason, the code encounters a cycle between 13 and 19. I don't think I can righteously proceed onto non-brute methods unless I can first get the brute-force method to at least compute correctly. My code looks like this:
unsigned int loop(unsigned int n)
{
unsigned int count = 0;
while(1)
{
while(is_even(n))
{
n /= 2;
}
if(n > 1)
n = (n * 3) + 1;
else
break;
count++;
printf("%d,", n);
}
printf("%d\n", n);
return count;
}
is_even(n) is computed as "n & 0x01".
Can anyone tell me why the output is a continuous (and theoretically endless) stream of "13,19," repeated?
Upvotes: 0
Views: 400
Reputation: 129149
n & 0x01
will be 1
if n
is odd, not if it is even. Change is_even
to return !(n & 0x01)
.
Upvotes: 3