Most efficient code for the first 10000 prime numbers?

前端 未结 30 1480
日久生厌
日久生厌 2020-11-29 19:09

I want to print the first 10000 prime numbers. Can anyone give me the most efficient code for this? Clarifications:

  1. It does not matter if your code is ineffici
30条回答
  •  清歌不尽
    2020-11-29 19:24

    Sieve of Eratosthenes is the way to go, because of it's simplicity and speed. My implementation in C

    #include 
    #include 
    #include 
    #include 
    
    int main(void)
    {
        unsigned int lim, i, j;
    
        printf("Find primes upto: ");
        scanf("%d", &lim);
        lim += 1;
        bool *primes = calloc(lim, sizeof(bool));
    
        unsigned int sqrtlim = sqrt(lim);
        for (i = 2; i <= sqrtlim; i++)
            if (!primes[i])
                for (j = i * i; j < lim; j += i)
                    primes[j] = true;
    
        printf("\nListing prime numbers between 2 and %d:\n\n", lim - 1);
        for (i = 2; i < lim; i++)
            if (!primes[i])
                printf("%d\n", i);
    
        return 0;
    }
    

    CPU Time to find primes (on Pentium Dual Core E2140 1.6 GHz, using single core)

    ~ 4s for lim = 100,000,000

提交回复
热议问题