here i have written a program on (3n+1) problem.it’s also a problem from UVa. I believe it’s a known problem.but when i am going to submit it in that online judge community it is sending me a Time Exceeding Error. the time limit is 3 sec. I have done what my little knowledge can do. If anyone can help me with some more advice I would be glad. my code is:
#include <iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
int loop=1;
unsigned short *cyclelength;
while(loop=1){
unsigned int x,y,i,j,num,count=0,p,k,c,max;
for(;;){
cout<<"enter two integers. they must not be equal and must be between 1 and 1000000\n";
while(!(cin>>i>>j)){
cout<<"please enter a number\n";
cin.clear();
cin.ignore(1000,'\n');
}
if(i>=1 && i<1000000 && j>=1 && j<1000000 && i!=j){
break;
}
else{
printf("try the whole process again\n");
}
}
if(i>j){
x=i;
y=j;
}
else{
x=j;
y=i;
}/*making x always greater than y*/
cyclelength=(unsigned short *)malloc(1000000 *sizeof(unsigned short));
if (NULL==cyclelength){
printf("process aborted");
return 0;
}
else{
/*solution part for the range of number. and solution for each number put into cyclelength.*/
num=y;
while(num<=x){
p=1;
k=num;
while(k!=1){
if(k%2==0)
k=k/2;
else
k=3*k+1;
p+=1;
}
cyclelength[count]=p;
num+=1;
count+=1;
}
c=0;
max=cyclelength[c];
for(c=0;c<x-y-1;c+=1){
if(max<cyclelength[c+1]){
max=cyclelength[c+1];
}
}
free(cyclelength);
cyclelength = NULL;
cout<<i<<" "<<j<<" "<<max<<'\n';
}
}
}
The problem is that you are not allowing your program to end when online judging engine has finished providing inputs. You need to detect that the judging engine has finished providing inputs and then exit the program.
There is a sample code (in C) on their website here Spoiler Alert: This is actually a solution to 3n+1 problem that kind of explains this. Notice the following condition in Main.
This will keep the program running only while there are inputs to be processed.