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+1];
    //assume all nos. are primes
    //mark all of them as true
    memset(prime, true, sizeof(prime));
    //take first prime i.e. 2
    //and mark all of its multiples as false
    //apply same method to the next prime, i++
    //the outer loop finds the next prime 
    //while the inner loop removes all the 
    //multiples of the current prime
    for(int i=2; i<=sqrt(n); i++){
        if(prime[i] == true){
            for(int j=i*i; j<=n; j+=i){
                prime[j] = false;
            }
        }
    }
    printf("Primes <= %d:\n", n);
    for(int i=2; i<=n; i++){
        if(prime[i])
            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