Posts

Search

Sieve Algorithm for finding Prime Numbers

Write a C++ program to print all the prime numbers which is less than the given number using sieve algorithm.

Program :

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int a;
    cin>>a;
    int v[a]={0};
    for(int i = 2; i*i<=a;i++)
    {
        if(v[i]==0)
        {
            for(int j = i*i; j <= a;)
            {
                v[j]=1;
                j = j+i;
            }
        }
    } 
    for(int i = 2;i < a; i++)
    {
        if(v[i]==0)
         cout<<i<<endl;
    }
    return 0;
}