位数组实现用筛法(Sieve of Eratosthnes)计算素数

//

//  main.c

//  bitarray

//

//  Created by Cheney Shen on 11-4-16.

//  Copyright 2011年 __MyCompanyName__. All rights reserved.

//



#include <stdio.h>

#include <limits.h>

#include <string.h>

#include <time.h>



#define BITMASK(b)  (1 << ((b) % CHAR_BIT))

#define BITSLOT(b)  ((b) / CHAR_BIT)

#define BITSET(a, b)    ((a)[BITSLOT(b)] |= BITMASK(b))

#define BITCLEAR(a, b)  ((a)[BITSLOT(b)] &= ~BITMASK(b))

#define BITTEST(a, b)   ((a)[BITSLOT(b)] & BITMASK(b))

#define BITNSLOTS(nb)    ((nb + CHAR_BIT - 1) / CHAR_BIT)



#define MAX 100000



int main (int argc, const char * argv[])

{

    char bitarray[MAX];

    int i, j;

    time_t  start, end;

    memset(bitarray, 0, BITNSLOTS(MAX));

    

    time(&start);

    printf("It's %s\n", ctime(&start));

    for (i = 2; i < MAX; i++) {

        if(!BITTEST(bitarray, i)) {

            printf("%d\t", i);

            for (j = i<<1; j < MAX; j += i)

                BITSET(bitarray, j);

        }

    }

    time(&end);

    printf("\n");

    printf("Now it's is %s", ctime(&end));

    return 0;

}

你可能感兴趣的:(IE)