Most efficient code for the first 10000 prime numbers?

前端 未结 30 1410
日久生厌
日久生厌 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:25

    Using GMP, one could write the following:

    #include 
    #include 
    
    int main() {
      mpz_t prime;
      mpz_init(prime);
      mpz_set_ui(prime, 1);
      int i;
      char* num = malloc(4000);
      for(i=0; i<10000; i++) {
        mpz_nextprime(prime, prime);
        printf("%s, ", mpz_get_str(NULL,10,prime));
      }
    }
    

    On my 2.33GHz Macbook Pro, it executes as follows:

    time ./a.out > /dev/null
    
    real    0m0.033s
    user    0m0.029s
    sys    0m0.003s
    

    Calculating 1,000,000 primes on the same laptop:

    time ./a.out > /dev/null
    
    real    0m14.824s
    user    0m14.606s
    sys     0m0.086s
    

    GMP is highly optimized for this sort of thing. Unless you really want to understand the algorithms by writing your own, you'd be advised to use libGMP under C.

提交回复
热议问题