HTML & JS
#include<bits/stdc++.h> 
#include<cmath>
using namespace std; 

void SieveOfEratosthenes(int n);

int main(void){
    int n;
    cout<<"Enter the value of n: ";
    cin>>n;
    SieveOfEratosthenes(n);
    return 0;
}

void SieveOfEratosthenes(int n){
    bool prime[n/2];
    memset(prime, false, sizeof(prime));
    //2 is the only even prime
    //hence ignore it
    //skip all other even nos.
    //therefore start check from 3
    //and increment by 2 to check only odd nos.
    //mark true if it's a prime
    for(int i=3; i<sqrt(n); i+=2){
        if(prime[i/2] == false){
            for(int j=i*i; j<n; j+=i*2){ //i*2 to skip the even nos. in the multiplication table of i
                prime[j/2] = true;
            }
        }
    }
    printf("Primes <= %d:\n", n);
    printf("2 ");
    for(int i=3; i<n; i+=2){
        if(!prime[i/2])
            printf("%d ", i);
    }
    printf("\n");
}

Generated URL:

Output:

Enter the value of n: Primes <= 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 
Report Bug