Thursday, January 24, 2008

3n+1 problem : Problem No.100

#include<iostream>

using namespace std;

int cyc(int);

int main()

{

int a,b,i,t;

while(cin>>a>>b)

{

if(a==0 && b==0)

{

break;

}

else

{

t=0;

if(b>a)

{

for(i=a;i<=b;i++)

{

if(cyc(i)>t)

{

t=cyc(i);

}

}

}

else

{

for(i=b;i<=a;i++)

{

if(cyc(i)>t)

{

t=cyc(i);

}

}}

cout<<a<<" "<<b<<" "<<t<<endl;

}

}

}

int cyc(int n)

{

int i=1;

while(n!=1)

{

if((n%2)!=0)

{

n=3*n+1;

}

else

{

n=n/2;

}

i++;

}

return i;

}



Problem submitted with runtime = 0.860

Do comment for better algorithm or lesser runtime solution.


No comments: