Cod sursa(job #340347)

Utilizator sterepavelStere Pavel sterepavel Data 14 august 2009 12:55:36
Problema Ciurul lui Eratosthenes Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define MY_FILE_NAME "ciur"
time_t start_time;

void read_data( int *n )
{
	FILE *f = fopen( MY_FILE_NAME".in", "r" );
	fscanf( f, "%i", n );
}

void write_response( long long response )
{
	FILE *f = fopen( MY_FILE_NAME".out", "w" );
	fprintf( f, "%lli", response );
}

int main()
{
#ifdef _MSC_VER
	start_time = time( NULL );
#endif

	static int v[1000000] = {0};
	static int count[1000000] = {0};
	long long v_max = 0;
	int n = 0;
	int response = 1; // contine 1/1

	read_data( &n );

	// pregatim vectorul de numere prime
	v[v_max++] = 2;
	for ( int i = 3; i <= n; i++ ) {
		const int limit = (int) ( false /*i < 100000*/ ? i/2 : sqrt( (float) i ) );
		bool prim = true;
		for ( int j = 0; j < v_max && v[j] <= limit; j++ ) {
			if ( 0 == i % v[j] ) {
				prim = false;
				break ;
			}
		}
		if ( prim )
			v[v_max++] = i;
	}
	response = v_max;
	//printf( "rupe %i\n", v_max );
/*
	//calculam cate numere
	for( int i = 0; i< v_max; i++ )
		count[i] = n / v[i];
	// calculam
	response = n+n-1; // pt 1
	for ( int i = 0; i < v_max; i++ ) {
		for ( int j = i+1; j < v_max; j++ ) {
			int count_common = n / (v[i]*v[j]);
			response += count[i] + count[j] - 2*count_common;
		}
	}
	*/
	write_response( response );

#if 0
	// calculam
	for ( int i = 1; i <= n; i++ ) {
		for ( int j = i+1; j <= n; j++ ) {
			bool primes = true;
			for ( int k = 0; k < v_max; k++ ) {
				if ( 0 == i % v[k] && 0 == j % v[k] ) {
					primes = false;
					break ;
				}
			}
			if ( primes )
				response += 2;
		}
	}

	write_response( response );
#endif

#ifdef _MSC_VER
	int secs = (int) (time( NULL ) - start_time);
	printf( "***** %i secs\n", secs );
#endif

	return 0;
}