Showing posts with label Sieve. Show all posts
Showing posts with label Sieve. Show all posts

Saturday, June 29, 2013

Bitwise sieve

Here is an implementation of Bitwise sieve. For full explanation See this and this-

#define MAX 100000000//max num to prime
#define LMT 10000 //sqrt(MAX)

int flag[MAX/64];
int prime[100000000],total;

#define chkC(n) (flag[n>>6]&(1<<((n>>1)&31)))
#define setC(n) (flag[n>>6]|=(1<<((n>>1)&31)))

void sieve() 
{
	unsigned i,j,k;

	flag[0]|=0;
	for(i=3;i<LMT;i+=2)
		if(!chkC(i))
			for(j=i*i,k=i<<1;j<MAX;j+=k)
				setC(j);

	prime[(j=0)++] = 2;//prime starts from 0 position
	for(i=3;i<MAX;i+=2)
		if(!chkC(i))
		{
			prime[j++] = i;
			//printf("%d\n",primes[j-1]);
		}
	total = j-1;
}

Sieve of Eratosthenes (Prime Finding)

The most popular prime finding method aka Sieve of Eratosthenes.

#define MAX 35000
#define lim 200

bool a[MAX];
int prime[MAX];

void sieve()
{
	int i,j;
	a[0]=1;a[1]=1;          //1 denotes not prime

	for(i=3;i<=lim;i+=2)    //even numbers are exclusive
	{
		if(a[i]==0)     //0 denotes prime
		{
			for(j=i*i;j < MAX;j+=i)
				a[j]=1;
		}
	}

	prime[0]=2;
	j=1;
	for(i=3;i < MAX;i+=2)     //even numbers are exclusive
	{
		if(a[i]==0)
			prime[j++]=i;
	}
}