Monday, March 20, 2017

Sieve-All Primes from 2 to n

/*  Bismillahir Rahmanir Rahim
    Sieve-all primes from 1 to n
*/
#include<bits/stdc++.h>
#define ll long long
using namespace std;
bool ar[10000009];

void sieve(ll x){
    for(int i=3; i*i<=x; i+=2){
        if(ar[i]){
            for(int j=i*3; j<=x; j+=i*2) ar[j]=false;
        }
    }
}

int main(){
    ll n, k;
    while(cin>>n){
        memset(ar, true, sizeof(ar));
        sieve(n);
        cout<<2<<" ";
        for(k=3; k<=n; k+=2){
            if(ar[k])cout<<k<<" ";
        }
        cout<<endl;
    }
    return 0;
}

No comments:

Post a Comment