Cod sursa(job #1599034)

Utilizator TeodorCotetCotet Teodor TeodorCotet Data 13 februarie 2016 15:56:03
Problema Ciurul lui Eratosthenes Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
//============================================================================
// Name        : CirurEratostene.cpp
// Author      : Teodor Cotet
// Version     :
// Copyright   : Your copyright notice
// Description : Ciur ertostene,time: O(N * log log n) memory: O(N)* bits, Ansi-style
//============================================================================

#include <fstream>
#include <iostream>
#include <cstring>

using namespace std;

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

const int NMAX = 2000000;

unsigned int check[(NMAX + 1) / 32 + 1];

bool getElement(unsigned int check[], int index) {

	index--; //nu exista indexul = 0
	int pos = index & 31;
	index = index >> 5;

	return check[index] & (1 << pos);
}

void setElement(unsigned int check[], int index) {

	index--;
	unsigned int pos = index & 31;
	index = index >> 5;

	check[index] |= (1 << pos);
}

int eratostene(int x) {

	int nrPrimes = 0;

	for(int i = 2; i * i <= x; ++i) {
		if(getElement(check, i) == 0)
			for(int j = i * i; j <= x; j += i)
				setElement(check, j);
	}

	for(int i = 2; i <= x ; ++i)
		if(getElement(check, i) == 0)
			nrPrimes++;

	return nrPrimes;
}

int main() {

	int x;

	fin >> x;

	fout << eratostene(x);

	return 0;
}