Cod sursa(job #2259178)

Utilizator preda.andreiPreda Andrei preda.andrei Data 13 octombrie 2018 10:01:51
Problema Ciurul lui Eratosthenes Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>

using namespace std;

int GetBit(char num, int pos)
{
    if (num & (1 << pos)) {
        return 1;
    }
    return 0;
}

int Get(char vec[], int pos)
{
    int block = pos / 8;
    int offset = pos % 8;
    return GetBit(vec[block], offset);
}

void Set(char vec[], int pos, int val)
{
    int block = pos / 8;
    int offset = pos % 8;

    if (val == 1) {
        vec[block] |= (1 << offset);
    } else {
        vec[block] &= (~(1 << offset));
    }
}

char is_not_prime[2000000 / 8 + 5];

int main()
{
    ifstream fin("ciur.in");
    ofstream fout("ciur.out");

    int limit;
    fin >> limit;

    for (int i = 2; i <= limit; i += 1) {
        if (Get(is_not_prime, i)) {
            continue;
        }

        for (int j = i * i; j > 0 && j <= limit; j += i) {
            Set(is_not_prime, j, 1);
        }
    }

    int count = 0;
    for (int i = 2; i <= limit; i += 1) {
        if (!Get(is_not_prime, i)) {
            count += 1;
        }
    }

    fout << count << "\n";
    return 0;
}