#include <iostream>
#include <math.h>
using namespace std;
bool IsPrime(int n)
{
int i, j;
if (n == 2)
{
return true;
}
else if (n < 2 || n%2==0)
{
return false;
}
else
{
j = (int)sqrt(n + 1);
for (i = 3; i <= j; i = i + 2)
{
if (n % i == 0)
{
return false;
}
}
}
return true;
}
int PrintPrim(int n)
{
assert(n >= 7);
unsigned int *array = (unsigned int *)malloc(n*sizeof(unsigned int));
assert(array != NULL);
int k = 0;
array[k++] = 2;
array[k++] = 3;
array[k++] = 5;
array[k++] = 7;
for(int i=11; i<=n; i++)
{
if(i%2==0 || i%3==0 || i%5==0 || i%7==0) continue;
array[k++] = i;
}
int iCount = 4;
for(int i=5; i<k; i++)
{
if(true == IsPrime(array[i])) array[iCount++] = array[i];
}
for(int i=0; i<k; i++)
{
//cout << i << ":" << array[i] << "\n";
cout << array[i] << "\t";
}
free(array);
return k;
}
int main(int argc, char *argv[])
{
PrintPrim(1000);
return 0;
}
求素数
最新推荐文章于 2022-10-23 20:43:17 发布