【发布时间】:2013-10-03 13:19:31
【问题描述】:
好的,第一件事。是的,这个问题来自编程竞赛。不,我不是想作弊,因为比赛已经结束 4 小时前。我很确定我的代码是正确的,但比赛的编译器说它给出了错误的答案。我尝试了其他编译器,它说“超出时间限制”。
那么,首先,你能告诉我代码是否正确吗? [一位编译器说不是]
如果是,那么我怎样才能提高时间效率? [另一个编译器说它超出了时间限制]
问题 如果一个数大于 1 并且 除了 1 和它自己之外没有除数。前几个素数 是 2, 3, 5, 7, 11, 13,.. 等等。给定一个整数 X,找到 不小于X的最小素数
输入:第一行包含测试用例的数量T.T用例 跟随。每个测试用例由一个单独的整数 X 组成。
输出:输出 T 行,每个案例一个包含最小的 不小于X的素数
约束:1
样本输入:4 8 47 90 1130
样本输出:11 47 97 1151
这是我的解决方案:
int main()
{
int n;
long int x, i, a;
bool isPrime; // This flag will test if number is prime or not?
cin>>n; // Here "n" will represent the number of test cases
while(n)
{
cin>>x; // "x" is the number to be tested for the nth case
if(x<=2)
{
cout<<2<<endl; // All numbers smaller than 3 will have the smallest prime number as 2.
continue;
}
for(i=x;i<=1000000;i++) // Should I have checked values of "i" for odd numbers only? I forgot to try that... Would it have helped in reducing time complexity?
{
isPrime=true;
for(a=2; a<i; a++) // Okay I tried making it (i/2)+1 but then the compiler said that it was a wrong answer. I am skeptical though...
{
if(i%a==0 and i!=2)
isPrime=false;
}
if(isPrime==true)
{
cout<<i<<endl;
break;
}
}
n--;
}
return 0;
}
【问题讨论】:
-
你试过在你的机器上运行这个吗?也许编译器报告错误实际上是您的程序运行时间过长(至少超过了挑战施加的时间限制)。
-
是的,我在我的计算机上运行它并尝试了各种测试用例,例如:-5、0、1、2、3、50 所有这些数字都得到了正确的输出。提供的测试用例也很有效。
-
您应该为已经遇到的素数使用缓存。它可能加快了这个过程。此外,您不需要检查直到 i 的每个除数,只需要检查 sqrt(i)
-
你说“超过时间限制”,所以这意味着你的程序花费了很多时间,你需要提高性能。
-
"if(isPrime==true)" == "if(isPrime)"