Cod sursa(job #1302097)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 26 decembrie 2014 16:48:03
Problema Ciurul lui Eratosthenes Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <fstream>
#include <math.h>
using namespace std;

int getByte(int i);
int getBit(int i);

int main()
{
    int N, i, j, k = 0;

    ifstream f("ciur.in");
    f >> N;
    f.close();

    int totalBytes = N / 8 + 1;
    unsigned char v[totalBytes];

    for (i = 0; i < totalBytes; i++)
        v[i] = ~0;

    for (i = 3; i <= sqrt(N); i += 2)
    {
        if ((v[getByte(i)] >> getBit(i)) & 1)
            for (j = i * i; j <= N; j += i + i)
                v[getByte(j)] &= ~(1 << getBit(j));
    }

    if (N >= 2)
    {
        k++;
        for (i = 3; i <= N; i += 2)
            if ((v[getByte(i)] >> getBit(i)) & 1)
                k++;
    }

    ofstream g("ciur.out");
    g << k;
    g.close();

    return 0;
}

int getByte(int i)
{
    return i / 8;
}

int getBit(int i)
{
    return i % 8;
}