Project Euler Problem14

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

nn/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?



#include <bits/stdc++.h>
using namespace std;
bool max(int &last_max,int count,int &max_num,int i)
{
     if(count > last_max)
     {  
        last_max =count;
        max_num = i;

     }  

}
int main()
{
  int count = 0; 
  int last_max = -999;
  int max_num = 0;
   for(long long i=2; i<1000000; i++)
   {  
       count =0;
        for(long long j=i; j>1; )
        {
           count++;
              if(j%2 == 0)
                  j = j/2;
              else
                  j = 3*j + 1;
   
             if(j==1)
             {
                 count++;
                 break;
             }

   
        }
        max(last_max,count,max_num,i);
   }  
  cout << max_num <<endl;
}

Comments

Popular posts from this blog

Project Euler Problem7

Project Euler Problem9

Project Euler Problem8