素数检测(Eratosthenes算法)*
自己的理解:
判断n是否是素数,将所有小于等于n的数初始化为true,首先小于等于1的数一定不是素数,再从2开始一直到根号n的所有素数中,在这个范围内的数只要比n小的数里有它的倍数,就令它为false即为合数,最后判断n是true还是false,如果是true就是素数
代码
#include
#include
#include
#include<math.h>
using namespace std;
int Primes(int n)
{
if(n<=1) //小于等于1的都不是质数
return 0;
bool a[n+1];
for(int i=2; i<=n; i++)//将比n小的所有数都默认设为true
a[i] = true;
for(int i=2; sqrt(ii)<n; i++)
{
if(a[i] == true)
{
for(int j=i; ij<=n; j++)
{
a[i*j] = false;
}
}
}
if(a[n]==true)
{
return 1;
}
else
return 0;
}
int main()
{
int n;
scanf("%d",&n);
if(Primes(n)==1)
{
printf(“是素数”);
}
else
printf(“不是素数”);
}
测试