令Pi表示第i个素数。现任给两个正整数M <= N <= 104,请输出PM到PN的所有素数。
输入格式:
输入在一行中给出M和N,其间以空格分隔。
输出格式:
输出从PM到PN的所有素数,每10个数字占1行,其间以空格分隔,但行末不得有多余空格。
输入样例:
5 27输出样例:
11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103
// 注:测试点4始终没通过,不知道是什么原因,如果各位有知道的,麻烦指点一下,谢谢。
#include "iostream"
#include "vector"
#include "math.h"
//#include "stdio.h"
using namespace std;
int main()
{
int order_start = 0, order_end=0;
int count = 0;
vector<int> output;
bool flag = false;
cin >> order_start >> order_end;
for (int i = 2; i <= 10000; i++)
{
flag = true;
if (i % 2 == 0 && i != 2)
{
flag = false;
continue;
}
for (int j = 2; j <= sqrt(i); j++)
{
if (i%j == 0)
{
flag = false;
break;
}
}
if (flag)
{
count++;
if (count >= order_start&&count <= order_end)
{
output.push_back(i);
if (count == order_end)
break;
}
}
}
for (int i = 0; i < output.size(); i++)
{
if ((i+1) % 10 == 0)
cout << output[i] << endl;
else
{
if (i < output.size() - 1)
cout << output[i] << " ";
else
cout << output[i];
}
}
system("pause");
return 0;
}
// 判断素数的算法没有问题,修改了程序如下,测试通过。
for循环那里出现的问题,但是不知道到底是为什么?
参考链接:http://www.th7.cn/Program/cp/201505/445775.shtml
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
bool prime(int value)
{
if (value % 2 == 0 && value != 2)
{
return false;
}
for (int j = 2; j <= sqrt(value); j++)
{
if (value%j == 0)
{
return false;
}
}
return true;
}
int main()
{
int order_start = 0, order_end = 0;
int count = 0;
vector<int> output;
cin >> order_start >> order_end;
int figure = 2;
while (count <= order_end)
{
if (prime(figure))
{
count++;
if (count >= order_start&&count <= order_end)
{
output.push_back(figure);
}
}
figure++;
}
for (int i = 0; i < output.size(); i++)
{
if ((i + 1) % 10 == 0)
cout << output[i] << endl;
else if (i < output.size() - 1)
cout << output[i] << " ";
else
cout << output[i];
}
system("pause");
return 0;
}