代码改变世界

筛选法求素数

2010-09-26 19:28  wansishuang  阅读(173)  评论(0编辑  收藏  举报
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <assert.h>
//#include <string.h>


int main()
{
    int num;
    printf("Find primes up to: ");
    scanf("%d", &num);

    clock_t start, stop;
    assert((start = clock()) != -1);

    int * prime = malloc((num+1) * sizeof(int));

    memset(prime, 0, sizeof(int) * (num+1));

    prime[0] = 1;
    prime[1] = 1;
    int i, j;
    for(i = 2; i <= sqrt(num) + 1; i++)
    {
       if(prime[i] == 0)
       {
           for(j = 2 * i; j <= num;j = j + i)
           {
               prime[j] = 1;
           }
       }

    }
    assert((stop = clock()) != -1);

    double t = (double) (stop-start)/CLOCKS_PER_SEC;

    for(i = 0; i <= num; i++)
    {
       if(prime[i] == 0)   printf("%d ", i);
    }
    printf("\n");
    printf("Run time: %f\n", t);

    free(num);
    return 0;
}