10亿素数算法

  1. //计算10亿需要60MB内存,比普通的bit位算法节省一半内存
  2.  unsigned int PrimeCounter(unsigned int MaxNumber)
  3. {
  4.     const unsigned MachineLength = sizeof(unsigned int) << 3;
  5.     const unsigned int MaxSize = MaxNumber / (MachineLength<<1) + 1;
  6.     unsigned int* Number = new unsigned int[MaxSize];
  7.     memset(Number,0xFF,MaxSize*sizeof(unsigned int));
  8.     for(unsigned long long num = 3;num<MaxNumber;num+=2)
  9.     if(Number[num/(MachineLength<<1)] & (0x1L<<((num>>1) % MachineLength))) {
  10.         for(unsigned long long NotPrime = num * num;NotPrime < MaxNumber ;NotPrime += num ) 
  11.             if(NotPrime % 2)
  12.                 Number[NotPrime / (MachineLength<<1)] &= ~(0x1L << ((NotPrime>>1) % (MachineLength)));               
  13.         }
  14.     unsigned int counter = 1;
  15.     for(unsigned int num = 3;num < MaxNumber;num +=2)
  16.         if( Number[num /(MachineLength<<1)] & (0x1L<<(num>>1 % (MachineLength)))){
  17.             //cout << num << "/t";
  18.             counter ++;
  19.         }
  20.     delete []Number;
  21.     return counter;
  22. }
  23. int main()
  24. {
  25.     clock_t pretime = clock();
  26.     std::cout << "/nPrimeCounter(10000000)= "<<PrimeCounter(10000000) << std::endl;
  27.     std::cout << clock() - pretime <<"ms has used.";
  28.     std::cout <<std::endl;
  29.     system("pause");
  30.     return 0;
  31. }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值