Sunday, March 29, 2015

Sieve Algorithm of finding prime number

To find all the prime numbers less than or equal to a given integer n by Sieve Eratosthenes' method:

1.    Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
2.    Initially, let p equal 2, the first prime number.
3.    Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list.
      These numbers will be 2p, 3p, 4p, etc.; note that some of them may have already been marked.
4.    Find the first number greater than p in the list that is not marked.
      If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
Implementation No 1 of sieve algorithm in c:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

#define n 1000

using namespace std;
void sieve(int  num)
{
    int list[n],status[n];
    for(int i=0;i<num-1;i++)
    {
        list[i]=i+2;
        status[i]=1;
    }


   for(int i=0;i<=sqrt(num);i++)
   {
       if(status[i]==1)
       {
           for(int j=i+1;j<num-1;j++)
           {
               if(list[j]%list[i]==0) status[j]=0;
           }
       }
   }
    printf("Primes of %d is:\n",num);
    for(int i=0;i<num-1;i++)
        if(status[i]==1)  printf("%d\t",list[i]);


}

int main()

{
    int num;
while(1)
{

    printf("Enter Your number of range of Primes:\n");
    scanf("%d",&num);
    sieve(num);
}
    return 0;
}


No comments:

Post a Comment