UVA: 100 - The 3n + 1 problem - Solution in C/C++



Problem Name: The 3n+1 problem

Problem Source: Uva Online Judge

Problem No: 100

Problem Difficulty: Easy

Problem Link: Here

Submit Solution Here

Important Point

  • i can be bigger than j. if i is bigger than j then you have to run the loop from j to i;
  • i and j in the output must be same as input.
  • You have to count n=1 case.
  • You don't have to use long long. int is enough.
  • You have to run the loop including i and j.

Source Code


#include<bits/stdc++.h>  
 using namespace std;  
 //Code Written by Al Shah Reyaj  
 //BSMRSTU, Gopalganj, Bangladesh  
 /* ******* ****    **    *******  
   *   *  **    * *      *  
   *  *  **   *  *     *  
   ****   **   ********    *  
   * *   **  *    *   *  
   *  *   **  *     *  *  
   *  *  **** *      * *******  
 */  
 int fin(int n,int c)  
 {  
   c++;  
   if(n==1) return c;  
   if(n%2!=0) fin((3*n)+1,c);  
   else fin(n/=2,c);  
 }  
 int main()  
 {  
   int a,b;  
   while(cin>>a>>b)  
   {  
     int m=0;  
     int x=a,y=b;  
     if(a>b)  
     {  
       int x=a;  
       a=b;  
       b=x;  
     }  
     for(int i=a; i<=b; i++)  
     {  
       int l=fin(i,0);  
       if(l>m) m=l;  
     }  
     cout<<x<<" "<<y<<" "<<m<<endl;  
   }  
   return 0;  
 


Thanks for Reading This. Check our more Activities.


EmoticonEmoticon