Cod sursa(job #1457500)

Utilizator tony.hegyesAntonius Cezar Hegyes tony.hegyes Data 3 iulie 2015 15:30:21
Problema Ciurul lui Eratosthenes Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <iostream>
using namespace std;

bool isPrime(int);

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

	// PRIME NUMBER IDENTIFICATION
	n += (n % 2 == 0) ? -1 : 0;
	int ciur[(n / 2) + 1] = {0};
	int m = (n >= 1) ? 1 : 0;
	
	for (int i = 1; i <= (n / 2); i++) {
		if (ciur[i] == 0) {
			if (isPrime(i * 2 + 1)) {
				m++; 
				for (int j = i; j <= (n / 2); j += (i * 2 + 1)) {
					ciur[j] == 1;
				}
			}
		}
	}
	
	// OUTPUT
	ofstream outdata("ciur.out");
	outdata << m;
	outdata.close();
	
	return 0;
}


bool isPrime(int n) {
	if (n <= 1) {
		return false;
	}
	if (n == 2) {
		return true;
	}
	
	if (n % 2 == 0) {
		return false;
	}
	
	for (int i = 3; i * i <= n; i++) {
		if (n % i == 0) {
			return false;
		}
	}
	
	return true;
}