Saturday 20 July 2013

39. Write a C++ program to generate prime numbers up to n using Sieve of Eratosthenes method.

 Sieve of Eratosthenes:
Sieve of Eratosthenes

#include<iostream.h>
#define SIZE 100
int main()
{
int i,j,n,a[SIZE];
cout<<"Please enter the max limit to check whether prime or not :"<<endl;
cin>>n;
    for(i=2;i<=n;++i)
         a[i-2]=i;               //Storing the elements into Array Ex: a[5]=7
    for(i=2;i<=n;++i)    //value ie used to check it's multiples in Array
     {
        if(a[i-2]==0)         //value '0' indicates that it is divisible (not prime)
            continue;
        cout<<a[i-2]<<" is prime"<<endl;
        for(j=i+1;j<=n;++j)       //eliminating prime multiples
        {
              if(j%i==0)
              a[j-2]=0;
         }
     }
     return 0;
}

No comments:

Post a Comment