Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Euler Solution #14

Tags:

c#

I have the following problem (from ProjectEuler.net - Problem 14)

The following iterative sequence is defined for the set of positive integers:

n -> n/2 (n is even)
n -> 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

I used:

   static int road (int n)
   {
       int road = 0;
       while (n != 1)
       {
           if (n % 2 == 0)
               n = n / 2;
           else
               n = 3 * n + 1;
           road++;
       }
       return road;
   }
   static void Main(string[] args)
   {
       int max = 0, num = 0;
       for (int i = 1; i < 1000000; i++)
       {
           if (road(i) > max)
           {
               max = road(i);
               num = i;
           }
       }
       Console.WriteLine(num);
   }

But no output is printed.

like image 636
Novak Avatar asked Dec 12 '22 04:12

Novak


1 Answers

(I'm not going to give you a complete solution since Project Euler is intended to make you think, not us who already solved the problems.)

Try figuring out how large the values in your chain are going to be and keep in mind the limits for integral types.

like image 51
Joey Avatar answered Dec 14 '22 16:12

Joey