使用位掩码生成Prime会导致程序崩溃

时间:2016-04-16 15:24:48

标签: c++ c++11

在下面的代码中,我使用了bitmasking来生成素数但是它不能正常工作而不是这个程序崩溃了 跑步时。

#include <bits/stdc++.h>
#define maxn 65540
using namespace std;

int _c[(maxn>>6)+1];  //as we will be neede max

int  primes[maxn];


#define IsComp(n)  (_c[n>>6]&(1<<((n>>1)&31)))//to compare bit
#define SetComp(n) _c[n>>6]|=(1<<((n>>1)&31))//to set the bit
void prime_sieve() {
for (int i = 3; i <=maxn; i += 2)
    if (!IsComp(i))
        for (int j = i*i; j <=maxn; j += i+i)
            SetComp(j);//if the number is not primes then it is changed     to  1

primes[0]=2;//first prime is 2;
int   j=1;
for (int i=3; i <= maxn; i += 2)
    if (!IsComp(i))
        primes[j++]=i;//putting the value in primes array;
}
int main()
{

prime_sieve();//calling the function
//Prime();
}

1 个答案:

答案 0 :(得分:1)

据我所知 当外环(i)运行到46348时,它运行良好,因为i * i在2147483648范围内,但是当我变为46349时,j值存在整数溢出,它的值变为-2146737495,然后跟随setComp(j) )j为负数。