Project Euler Homework

014.cpp

Go to the documentation of this file.
00001 
00013 #include <iostream>
00014 using namespace std;
00015 
00016 class sequence
00017 {
00018   unsigned x;
00019 public:
00020     sequence (unsigned k)
00021   {
00022     x = k;
00023   }
00024   unsigned next ()
00025   {
00026     if (x & 1)                  //much more efficient than modulus
00027       x = x * 3 + 1;
00028     else
00029       x /= 2;
00030     return x;
00031   }
00032   bool end ()
00033   {
00034     return x == 1;
00035   }
00036 };
00037 
00038 class table_list                //look up table
00039 {
00040   bool list[500000];
00041 public:
00042     table_list ()
00043   {
00044     bool *p = list;
00045     for (unsigned k = 0; k < 500000; k++, p++)
00046        *p = 0;
00047   }
00048   void insert (unsigned k)
00049   {
00050     list[k - 500001] = 1;
00051   }
00052   bool find (unsigned k)
00053   {
00054     return list[k - 500001];
00055   }
00056 };
00057 
00072 int
00073 main ()
00074 {
00075   unsigned long long max_count = 0;
00076   unsigned starting_number;
00077 
00078   table_list table;
00079   //if k is found in this set, then length of sequence of k should be smaller.
00080 
00081   for (unsigned k = 500001; k < 1000000; k++)
00082     {
00083       if (table.find (k))
00084         continue;               //skip if k is in the table.
00085       sequence N (k);
00086       unsigned count = 1;
00087       while (!N.end ())
00088         {
00089           unsigned y = N.next ();
00090           if (y < 1000000 && y > k)
00091             table.insert (y);   //insert other exceptions
00092           count++;
00093         }
00094       if (count > max_count)
00095         {
00096           starting_number = k;
00097           max_count = count;
00098         }
00099     }
00100   cout << starting_number << endl;
00101   return 0;
00102 }
00103 
 All Classes Files Functions Variables