#include<stdio.h>
#include<math.h>
#include<malloc.h>
void Erastothenes(int N);//寻找小于N的素数,该方法称为Erastothenes筛
int main(void)
{
int N = 100;
Erastothenes(N);
return 0;
}
void Erastothenes(int N)
{
int* arr = (int*)malloc(sizeof(int) * N);
for (int i = 0; i < N; i++)
arr[i] = 1;
for (int i = 2; i < sqrt(N); i++)
{
if (arr[i] == 1)//以i=2为例,给i=4,6,8...赋值为0,没有该if语句i=4,6,8...时会重复赋值
{
for (int j = 2 * i; j < N; j = j + i)
arr[j] = 0;
}
}
for (int i = 2; i < N; i++)
{
if (arr[i] == 1)
printf("%d ", i);
}
}
《数据结构与算法分析:C语言描述》习题2.14
最新推荐文章于 2022-04-24 09:22:36 发布