原文链接: 位运算的素数筛法
上一篇: c++ 位运算 和 掩码
下一篇: ros 安装 环境 配置
对32位整数,使用bool数组表示是否为素数,需要2^32字节,即4g内存
将偶数去除,也需要2g内存
使用位标志,可以将内存减少到八分之一
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
// 最大的数字
const unsigned int MAX_N = 1 << 20;
// 需要判断的数字个数,1个字节8位
unsigned char sieve[(MAX_N + 7) >> 3];
// 确认k是否为素数
bool isPrime(int k){
return sieve[k >> 3] & (1 << (k & 7) );
}
// 标记k不是素数
void setComposite(int k){
sieve[k >> 3] &= ~(1 << (k & 7) );
}
void eratosthenes(){
/