天天看点

快速求素数的方法, 100million 花费大概30second!

原始c、c++代码如下

应该是比较有效算法,如有更进一步优化,恳请不吝赐教!

#include <iostream>
#include <time.h>
#include <stdint.h>

char* primeNumbersBySieveOfEratosthenes(long long n)
{
  char* num = new char[sizeof(char) * n]();

  long long i = 2;
  while ( i * i  <= n )
  {
       for (long long c = 2, idx = 2*i; idx < n; ++c, idx = i * c)
       {
          num[idx] = true;
       }

       do{
          ++i;
       } while ( i * i <= n && num[i] == true);
  }

  return num;
}

int main()
{
    struct timespec first, second;
    clock_gettime(CLOCK_REALTIME, &first);
    long long max_long = 1000000000L;
    long long tmpresult=0L;
    char* result = primeNumbersBySieveOfEratosthenes(max_long);

    for (long long i=0; i<max_long; i++){
        if (!result[i]) {
          tmpresult += i;
        }
    }
    
    clock_gettime(CLOCK_REALTIME, &second);
    unsigned long long resultTime = (second.tv_sec - first.tv_sec)*1000000 + (second.tv_nsec - first.tv_nsec) / 1000;
    std::cerr << "[" <<  tmpresult << "] resultTime = " << resultTime << std::endl;
    return 0;
}
           

继续阅读