Cod sursa(job #2702653)

Utilizator vnedelcuVictor Andrei Nedelcu vnedelcu Data 5 februarie 2021 10:49:59
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;
        }
        // j increases by 2i because 
        // we have to make sure that j is odd
        for (int j = i * i; j <= n; j += (i << 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;
}