在这里,我编写了一个关于 (3n+1) 问题的程序。这也是 UVa 的一个问题。我相信这是一个已知问题。但是当我要在该在线法官社区中提交它时,它会向我发送Time Exceeding Error。时间限制为 3 秒。我已经做了我的小知识可以做的事情。如果有人可以帮助我提供更多建议,我会很高兴。我的代码是:
#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';
}
}
}