【发布时间】:2013-11-20 18:18:33
【问题描述】:
我必须找到 t 个案例的素数。以下输入/输出示例:
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
还要注意答案之间的空格。
#include <iostream>
#include <cmath>
bool prime (int x, int y);
using namespace std;
int main()
{
int t, x, y;
cin >> t;
for(int i = 0; i < t; i++)
cin >> x >> y;
for(int i = 0; i < t; i++){
for (int i = x; i <= y; i++)
cout << prime(x, y) << endl;
}
return 0;
}
bool prime(int x, int y){
bool prime = true;
for (int i = x; i <= y; i++){
for (int j = 2; j <= sqrt(i); j++)
if (i % j == 0)
prime = false;
return prime;
}
}
我的程序一直只输出1,这是为什么呢?
【问题讨论】:
-
t 表示测试用例的数量
-
你有一个函数,如果范围内的任何数字是素数,则返回
true,然后你继续调用它并打印结果。也许你应该找到一组素数并打印出每一个。 -
我不知道它会对您的程序产生多大的影响,但我建议您将
main()中的内部循环更改为使用i以外的变量名。最好不要掩盖这样的变量。 -
最好使用offset sieve of Eratothenes。 C 代码here。您必须提前知道您的测试范围,或者您必须根据需要扩展核心数组。