Cod sursa(job #2702576)

Utilizator vnedelcuVictor Andrei Nedelcu vnedelcu Data 4 februarie 2021 19:41:20
Problema Ciurul lui Eratosthenes Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <vector>

using namespace std;

int main() {
    int n;
    ifstream fin("ciur.in");
    fin >> n;
    fin.close();

    // sieve[i] = true if (i * 2 + 1)-th number is prime
    vector<bool> sieve((n + 2) >> 1, true);

    int no_primes_le_n = 1; // 2 is a prime
    for (int i = 3; i * i <= n; i += 2) {
        if (sieve[(i - 1) >> 1] == false) {
            continue;
        }
        for (int j = i * i; j <= n; j += i) {
            // we have to make sure that j is odd
            if (j & 1) {
                sieve[(j - 1) >> 1] = false;
            }
        }
    }

    for (int i = 3; i <= n; i += 2) {
        if (sieve[(i - 1) >> 1] == true) {
            no_primes_le_n++;
        }
    }

    ofstream fout("ciur.out");
    fout << no_primes_le_n;
    fout.close();

    return 0;
}