Cod sursa(job #1202922)

Utilizator andreioneaAndrei Onea andreionea Data 30 iunie 2014 02:30:30
Problema Ciurul lui Eratosthenes Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <cstring>

#define INFILE "ciur.in"
#define OUTFILE "ciur.out"

using std::ifstream;
using std::ofstream;
using std::memset;

typedef long word_type;
const int word_size = sizeof(word_type) * 8;

class BitVector 
{
public:
	BitVector(int n) : data(0), n(n)
	{
		int words = n / word_size + (((n % word_size) > 0) ? 1 : 0);
		data = new word_type[words];
		memset(data, 0, words * sizeof(word_type));
	}
	~BitVector()
	{
		delete[] data;
	}
	bool operator[](int idx) {
		if (idx > n)
			return false;
		return (data[idx / word_size] >> (idx % word_size)) & 1;
	}
	void set(int idx)
	{
		if (idx <= n)
		{
			data[idx / word_size] |= (1 << (idx % word_size));
		}
	}
private:
	word_type *data;
	int n;
};

int main()
{
	ifstream fin(INFILE);
	ofstream fout(OUTFILE);
	int n;
	fin >> n;
	fin.close();
	BitVector v(n);
	v.set(0);
	v.set(1);
	auto res = 0;
	for (auto i = 2; i <= n; ++i) {
		if (!v[i]) {
			++res;
			auto x = i * 2;
			while (x <= n) {
				v.set(x);
				x += i;
			}
		}
	}
	fout << res;
	fout.close();
	return 0;
}