Cod sursa(job #1457549)

Utilizator tony.hegyesAntonius Cezar Hegyes tony.hegyes Data 3 iulie 2015 17:01:11
Problema Ciurul lui Eratosthenes Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
using namespace std;

///// DESCRIPTION
// THIS PROGRAM FINDS ALL PRIME NUMBERS
// LESS OR EQAUL TO n BY EMPLOYING 
// THE SIEVE OF ERASTOTHENES
/////

int main(int argc, char **argv)
{
	// INPUT
	int n;
	ifstream indata("ciur.in");
	indata >> n;	
	indata.close();

	// PRIME NUMBER IDENTIFICATION
	
	// except for 2, no even number is prime
	// so we can only check the odd numbers
	int cnt = (n >= 2) ? 1 : 0; // the program doesn't test afterwards if 2 is prime
	n += (n % 2 == 0) ? -1 : 0; // make sure n is always an odd number
	
	// assume all numbers between 3 and n are prime
	// each number is retrieved as (i * 2 + 1), i between 1 and [n/2]
	bool prime[(n / 2) + 1];
	for (int i = 0; i <= (n / 2); i++) {
		prime[i] = true;
	}
	
	// see which ones between 3 and n truly are prime
	for (int i = 1; i <= (n / 2); i++) {
		if (prime[i] == true) {
			cnt++;
			// if this number is prime, all multiples cannot be prime
			// --> mark all (odd) multiples of this number as non-prime
			for (int j = 3 * i + 1; j <= (n / 2); j += (i * 2 + 1)) {
				prime[j] = false;
			}
		}
	}
	
	// OUTPUT
	ofstream outdata("ciur.out");
	outdata << cnt;
	outdata.close();
	
	return 0;
}