算法分析
1、判断是否是素数:只能被1和自己整除的素为素数,即不能被2到这个数的平方根整除的数为素数。
2、遍历区间帅选是否为素数
c++代码
#include <iostream>
#include <math.h>
using namespace std;
//判断是否为素数:是否能被2和自己的平方根之间的数整除
bool IsPrime(int n)
{
//最小的素数是2
if(n == 1)
{
return false;
}
for(int i = 2; i <= sqrt((double)n); i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}
//输出两个数之间的素数,m<n
void PrintPrimes(int m,int n)
{
for(int i = m; i <=n; i++)
{
if(IsPrime(i))
{
cout<<i<<", ";
}
}
cout<<endl;
}
测试代码
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"please input m and n"<<endl;
int m = 0;
int n = 0;
cin>>m;
cin>>n;
if(m>n)
{
PrintPrimes(n,m);
}
else
{
PrintPrimes(m,n);
}
return 0;
}


被折叠的 条评论
为什么被折叠?



