views:

101

answers:

3

I am working on Problem 14 on Project Euler, and my code seems to freeze at random intervals for no apparent reason.

static void Main()
{
    int maxNum = 0;
    int maxLength = 0;
    for (int x = 2; x < 1000000; ++x)
    {
        int num = x;
        int length = 0;
        while (num != 1)
        {
            if (num % 2 == 0)
            {
                num /= 2;
                length++;
            }
            else
            {
                num = (3 * num) + 1;
                length++;
            }
       }
       if (length > maxLength)
       {
            maxLength = length;
            maxNum = x;
       }
    }
    Console.WriteLine(maxNum);
    Console.ReadLine();

The number that the program hangs at is different each time I run it and doesn't seem to follow any set patterns. Any ideas on why it would be hanging like this? Thanks in advance.

A: 

If goes into infinite loop in while (num != 1).

Incognito
You've just solved a major problem! got place for the proof?
Kobi
That just the thing though. I don't think it does go into an infinite loop, because sometimes it get stuck at a certain number and other times it does not.
APShredder
+3  A: 

I've solved it in another way, by caching the result for each step, and I've found your problem. I doubt your program ever stops.
The statement num = (3 * num) + 1 may overflow over Int32.MaxValue and result in a negative number and an infinite loop(?).
In this case, you can solve the problem by using long for your x.

Kobi
Yep that seems to be the problem. I changed int to long and it works great now. Thanks!
APShredder
No problem, it's a fun puzzle. Here's my solution, if you're interested: http://pastebin.com/xpvK0nBC
Kobi
A: 

I bet that this version doesn't freeze, there's no reason it should do that.

The Collatz sequences before you hit 1 in the inner while loop are too short to lead to a noticeable delay, and if they would that should always happen at the same numbers.

If you add console output inside the loop then this may allocate memory, and the pauses you see could be due to garbage collection.

starblue
The problem is integer overflow in this case which *definitely* happens for the scope of that problem. Threw me off a bit as well back when I re-wrote my solution in C and C#.
Joey
Yes, I forgot that. With 32 bit integer overflow there are many loops, for example at 113383. Though in that case it should always hangs at this number.
starblue