15 July 2010

Find Primes: Sieve of Eratosthenes

//very simple implementation for "Sieve of Eratosthenes" 
//to find primes
//http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
//@auther mhewedy

#include <stdio.h>

#define MAX_PRIME 150

int main(void){

int arr[MAX_PRIME], i, j;

for (i=0; i<MAX_PRIME; i++) arr[i] =1;

arr[0] = arr[1] = 0;

for (i=2; i<MAX_PRIME; i++){
if (arr[i] != 0){
arr[i] = 1;
for (j=2; j<MAX_PRIME;j++)
if (j!=i && j%i == 0)
arr[j] =0;
}
}

for (i=0; i<MAX_PRIME; i++)
if (arr[i]) printf("%i ", i);

printf("\n");

return 0;
}

Post a Comment