Cod sursa(job #1202920)

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

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

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

class BitVector 
{
public:
	BitVector(int n) : n(n), data(0) 
	{
		int bytes = n / 8 + (((n % 8) > 0) ? 1 : 0);
		data = new char[bytes];
		memset(data, 0, bytes);
	}
	~BitVector()
	{
		delete[] data;
	}
	bool operator[](int idx) {
		if (idx > n)
			return false;
		return (data[idx / 8] >> (idx % 8)) & 1;
	}
	void set(int idx)
	{
		if (idx <= n)
		{
			data[idx / 8] |= (1 << (idx % 8));
		}
	}
private:
	char *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;
}