-1

The link to the 3n+1 problem on UVa is: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36

My code is :

#include<iostream>
using namespace std;


long long l(long long n)
{
        if(n==1)
        {
                return 1;
        }
        if(n%2)
        {
                return 1+l(3*n+1);
        }
        else
        {
                return 1+l(n/2);
        }
}


int main()
{
        long long i,j,k,max=0,f,g;
        while(!cin.eof())
        {
                cin>>i>>j;
                f=i;
                g=j;
                if(i>j)
                {
                        long long temp;
                        temp=i;
                        i=j;
                        j=temp;
                }
                max=0;
                for(long long a=i;a<=j;a++)
                {
                        k=l(a);
                        if(k>max)
                        {
                                max=k;
                        }
                }
                cout<<f<<' '<<g<<' '<<max<<'\n';
        }   
        return 0;
}

To explain my code, I'm using simple recursion. The input is taken as i, j and is preserved as it is using f, g respectively. i and j are swapped explicitly using temp. max is set 0 in every test case. k is used to hold the result sent by length function l() and is tested with max which stores maximum length till now.

My solution passes all the given trivial test cases in the problem. It even passes all the tricky test cases which involve i greater than j and i==j The problem hides integer overflow by giving incomplete information about requirement of long. I even handled that. The output rquires i, j in same order. The input gives no explicit end. I handled all of them. But still am getting wrong answer.

2 Answers2

0

Your code is okay.
The only problem is your input handling untill End of File.
Just change while(!cin.eof()) to while(cin>>i>>j). You will get AC :)

Ali Akber
  • 3,217
  • 2
  • 21
  • 37
0

May be problem with '\n'? Try to use cout<<f<<' '<<g<<' '<<max<<endl;