题目:
令 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
思路:
应该先找到第M个素数和第N个素数,然后在这个区间里遍历找素数,找到素数后就按照格式输出
代码:
#include<iostream>
#include<cmath>
using namespace std;
bool isPrime(int num);
int main()
{
int m,n,less_prime,greater_prime,t=2,count_num=0,count_row=0;
bool getLess=false;
cin>>m>>n;
while(true)
{
if(isPrime(t))
count_num++;
if(count_num==m&&!getLess)//getLess的目的是因为count_num可能在几次循环中都是等于m的,会多次执行less_prime=t,
{ //但是在每次循环中,t是一直变化的,所以如果不加一个判断条件的话less_prime值是错误的
getLess=true;
less_prime=t;
}
if(count_num==n)
{
greater_prime=t;
break;
}
t++;
}
for(int i=less_prime;i<=greater_prime;i++)
{
if(isPrime(i))//在less_prime和greater_prime之间找素数,是的话就按照格式输出
{
cout<<i;
count_row++;
if(count_row%10==0)
{
if(i!=greater_prime)
cout<<"\n";
}
else
{
if(i!=greater_prime)
cout<<" ";
}
}
}
return 0;
}
bool isPrime(int num)
{
if(num<=1)
return false;
for(int i=2;i<=sqrt(num);i++)
{
if(num%i==0)
return false;
}
return true;
}
心得:
通常情况下可能很难一次性写对,多思考,多举例,多试验
来源:CSDN
作者:笑笑逍遥生
链接:https://blog.csdn.net/qq_40930559/article/details/104082381