筛法查找素数
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MALLOC(p, n, t)\
if(!(p = malloc((n) * sizeof(t)))) {\
fprintf(stderr, "malloc error...");\
exit(EXIT_FAILURE);\
}
#define FREE(p) if(p) free(p), p = NULL
typedef unsigned long long ULL;
void filter(ULL [], ULL);
ULL prtnum(ULL [], ULL);
int main(void) {
clock_t begin, end;
double total;
ULL *num = NULL, i, x, y, len, count;
printf("查找某个整数区间内素数 (下限x>=2 上限y>=x) : ");
if(scanf("%lld%lld", &x, &y) != 2 || x < 2 || x > y)
exit(EXIT_FAILURE);
len = y - x + 1;
MALLOC(num, len, ULL);
for(i = 0; i < len; i++)
num[i] = x + i;
begin = clock();
filter(num, len);
end = clock();
total = (double)(end - begin) / CLOCKS_PER_SEC;
count = prtnum(num, len);
printf("区间内共有 %llu 个素数...\n", count);
printf("任务用时: %f 秒...\n", total);
FREE(num);
return 0;
}
void filter(ULL num[], ULL len) {
ULL i, j, k, t;
for(i = 0; i < len; i++)
if(num[i])
for(t = sqrt(num[i]), j = 2; j <= t; j++)
if(num[i] && num[i] % j == 0)
for(k = 0; i + j * k < len; k++)
num[i + j * k] = 0;
}
ULL prtnum(ULL num[], ULL len) {
ULL i, count = 0;
for(i = 0; i < len; i++) {
if(num[i]) {
printf("%llu ", num[i]);
count++;
}
}
printf("\n");
return count;
}









