| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 419 人关注过本帖
标题:筛法查找素数
只看楼主 加入收藏
longwu9t
Rank: 11Rank: 11Rank: 11Rank: 11
等 级:小飞侠
威 望:6
帖 子:732
专家分:2468
注 册:2014-10-9
结帖率:100%
收藏
 问题点数:0 回复次数:1 
筛法查找素数
程序代码:
#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;
}
2015-03-20 11:07
wp231957
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
来 自:神界
等 级:贵宾
威 望:423
帖 子:13688
专家分:53332
注 册:2012-10-18
收藏
得分:0 
标记  我不习惯使用宏 比较喜欢函数

DO IT YOURSELF !
2015-03-20 14:19
快速回复:筛法查找素数
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.017545 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved