Preview:
#include <iostream>
#include <vector>
using namespace std;
void sieve_of_eratosthenes(int n) {
    vector<bool> is_prime(n + 1, true); // Initialize all entries as true
    is_prime[0] = is_prime[1] = false;  // 0 and 1 are not prime numbers
    for (int i = 2; i * i <= n; i++) {
        if (is_prime[i]) {
            // Mark all multiples of i as false
            for (int j = i * i; j <= n; j += i) {
                is_prime[j] = false;
            }
        }
    }

    // Output all prime numbers
    cout << "Prime numbers up to " << n << " are:" << endl;
    for (int i = 2; i <= n; i++) {
        if (is_prime[i]) {
            cout << i << " ";
        }
    }
    cout << endl;
}

int main() {
    int n = 50;
    sieve_of_eratosthenes(n);
    return 0;
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter