Wednesday, February 22, 2012

My UVA 100 3n+1 Problem solution


http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36





#include<iostream>


#define rep(i,a,b) for(int i=a;i<=b;i++)


using namespace std;


long trace2(long n)
{
    if(n<=1)return 1;
    
    long next1;
    if(n%2==0)
      next1=n/2;
    else
      next1=3*n+1;
    
    return trace2(next1)+1;
}


int main(int argc, char *argv[])
{
    int I=0,J=0,R=0;
    while(cin>>I>>J)
    {
        long t,max=0;
        if(I<J)
        {
            rep(i,I,J)
            {
                t=trace2(i);
                if(t>max){max=t;}
            }
        }
        else
        {
            rep(i,J,I)
            {
                t=trace2(i);
                if(t>max){max=t;}
            }
        }
        cout<<I<<" "<<J<<" "<<max<<endl;
    }
    return 0;
};

No comments:

Post a Comment