C++ Programming Blog

 
 
 

Image

 # include <iostream.h>
 # include <fstream.h>
 # include <string.h>
 # include <stdlib.h>
 # include <conio.h>

 const long cycle_length(long);
 const long max_cycle_length(const long,const long);


 int main( )
    {
       clrscr( );

       fstream File(\"CP-19.txt\",ios::in|ios::nocreate);

       if(!File)
      {
         cout<<\"\\n Unable to open the input file.\"<<endl;
         cout<<\"\\n Press any key to exit.\";

         getch( );
         exit(EXIT_FAILURE);
      }

       char Data[100]={NULL};

       do
      {
         strset(Data,NULL);

         File.getline(Data,80);

         if(strcmp(Data,NULL)==0)
        break;

         long start=0;
         long end=0;

         char* Ptr=NULL;

         Ptr=strtok(Data,\" \");
         start=atol(Ptr);

         Ptr=strtok(NULL,\"\\n\");
         end=atol(Ptr);

         cout<<start<<\" \"<<end<<\" \"<<max_cycle_length(start,end)<<endl;
      }
       while(1);

       File.close( );

       getch( );
       return 0;
    }



 //-------------------------  max_cycle_length( )  -----------------------//


 const long max_cycle_length(const long start,const long end)
    {
       long length=0;
       long max_length=0;

       for(long i=start;i<=end;i++)
      {
         length=cycle_length(i);

         if(length>max_length)
        max_length=length;
      }

       return max_length;
    }


 //--------------------------  cycle_length( )  --------------------------//


 const long cycle_length(long n)
    {
       long length=1;

       while(n!=1)
      {
         if((n%2)==0)
        n=(n/2);

         else
        n=((3*n)+1);

         length++;
      }

       return length;
    }