寻找大于2^N的最小质数

最近需要个序列,要求接近2的幂,但又不能有公因子。为免除后患,决定取大于2^N的最小质数。

希望至少找到2^33次方,选用了筛法。由于需要8G以上内存,程序编译模式得选x64:

(BTW:编写时发现VC++的new操作不能分配超过0x7FFFFFFF的内存,而malloc可以)

// prime_sieve_cpp.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include 
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
  __int64 const K = 1024;
  __int64 const M = 1024 * K;
  __int64 const G = 1024 * M;
  __int64 const T = 1024 * G;

  __int64 const N = 9 * G + 100000;
  char * a = (char*)malloc(N);
  for(__int64 i = 0; i < N; ++i){
    a[i] = 1;
  }
  a[0] = 0;
  a[1] = 0;

  for(__int64 i = 2; i < N; ++i){
    if(a[i]){
      for(__int64 j = i + i; j < N; j += i){
        if(a[j]){
          a[j] = 0;
        }
      }
    }
    //if((i % MB) == 0){
    //  cout << (i / MB) << "mb" << endl;
    //}
  }

  __int64 n = 2, pw = 1;
  while(n < N){
    cout << "least prime over 2^" << setw(2) << pw << "(" << setw(14) << n << "): ";
    for(__int64 i = n; i < N; ++i){
      if(a[i] == 1){
        cout << i;
        break;
      }
    }
    cout << endl;

    n *= 2;
    ++pw;
  }

  free(a);
	return 0;
}


结果:

least prime over 2^ 1( 2): 2
least prime over 2^ 2( 4): 5
least prime over 2^ 3( 8): 11
least prime over 2^ 4( 16): 17
least prime over 2^ 5( 32): 37
least prime over 2^ 6( 64): 67
least prime over 2^ 7( 128): 131
least prime over 2^ 8( 256): 257
least prime over 2^ 9( 512): 521
least prime over 2^10( 1024): 1031
least prime over 2^11( 2048): 2053
least prime over 2^12( 4096): 4099
least prime over 2^13( 8192): 8209
least prime over 2^14( 16384): 16411
least prime over 2^15( 32768): 32771
least prime over 2^16( 65536): 65537
least prime over 2^17( 131072): 131101
least prime over 2^18( 262144): 262147
least prime over 2^19( 524288): 524309
least prime over 2^20( 1048576): 1048583
least prime over 2^21( 2097152): 2097169
least prime over 2^22( 4194304): 4194319
least prime over 2^23( 8388608): 8388617
least prime over 2^24( 16777216): 16777259
least prime over 2^25( 33554432): 33554467
least prime over 2^26( 67108864): 67108879
least prime over 2^27( 134217728): 134217757
least prime over 2^28( 268435456): 268435459
least prime over 2^29( 536870912): 536870923
least prime over 2^30( 1073741824): 1073741827
least prime over 2^31( 2147483648): 2147483659
least prime over 2^32( 4294967296): 4294967311
least prime over 2^33( 8589934592): 8589934609

你可能感兴趣的:(算法,C++)