Pages

Saturday, January 8, 2011

Sieve Algorithm Implimentation

Sieve is a popular algorithm. It is used to detect the prime numbers between two numbers.  

Code:
#include<stdio.h>
#include<math.h>
#define max 10000000
char p[max];
void sieve()
{
long i,j,c=0,x=0;
for(i=2;i<max;i++) p[i]=1;
for(i=2;i<=sqrt(max); )
{

for(j=i+i;j<=max;j+=i)
p[j]=0;
i++;
for( ;!p[i];i++);
}
for(i=0;i<=max;i++)if(p[i])x++; /*This 2 lines for checking the number of primes between 0 & 10000000.*/
printf("%d",x);

}
int main()
{
sieve();
return 0;
}