Cod sursa(job #555309)

Utilizator svoprea1Silviu Vlad Oprea svoprea1 Data 15 martie 2011 13:37:46
Problema Fractii Scor 0
Compilator c Status done
Runda Arhiva de probleme Marime 0.96 kb
#include <stdio.h>

int
n_p(int);

int
main()
{
	long   n, rez;
	FILE  *f;

	if ((f = fopen("fractii.in", "r")) == NULL)
	{
		perror("Cannot open destination file...\n");
		return -1;
	}

	if (fscanf(f, "%ld", &n) != 1)
	{
		printf("Cannot read from file ...\n");
		return -1;
	}

	if (fclose(f) == EOF)
		perror("Cannot close source file...\n");

	if ((f = fopen("fractii.out", "w")) == NULL)
	{
		perror("Cannot open destination file...\n");
		return -1;
	}

	rez = n * n - 2 * n_p(n) - n + 1;
	// printf("Result: %ld\n", rez);
	if (fprintf(f, "%ld", rez) < 0)
	{
		printf("Cannot write to file...\n");
		return -1;
	}

	if (fclose(f) == EOF)
	{
		perror("Cannot close destination file...\n");
		return -1;
	}

	return 0;
}

int
n_p(int n)
{
	long i, j, k, reductible = 0;

	for (i = 2; i <= n; i++)
	{
		for (k = 2; k <= i; k++)
		{
			if (i % k == 0)
			{
				j = i + k;
				while (j <= n)
				{
					reductible += n / j;
					j = j + i;
				}
			}
		}
	}
	return reductible;
}