Cod sursa(job #347900)

Utilizator grozaviorelGroza Viorel Mihai grozaviorel Data 13 septembrie 2009 14:34:01
Problema Cifra Scor 0
Compilator c Status done
Runda Arhiva de probleme Marime 2.58 kb
#include <stdio.h>

//Calculate the last digit of f(n) =  1^1 + 2^2 + 3^3 + .. n^n

#define DEBUG

//The key is that f is a periodical function

#define PERIOD 100						 

#ifdef DEBUG
//Debug version..only for tests - periodic function
int power_mod(int n)
{
	int power = 1;
	
	int last_digit = n % 10;
	int i = 0;
	
	for (i = 0; i < n; i++)
	{
		power = ((power % 10) * last_digit) % 10;
	}
	
	return power;
}

int show_numbers(int n)
{
	int s = 0;
	int i = 0;
	char c = 0;
	
	FILE* pOutputFile = NULL;
	pOutputFile = fopen("numbers.txt", "w");
	
	for (i = 1; i <= n; i++)
	{
		s += power_mod(i);
		s %= 10;
		fprintf(pOutputFile, "%d %d \n", i, s);
	}
	
	fclose(pOutputFile);
	return 0;
}

int main()
{	
	FILE* fInput  = NULL;
	FILE* fOutput = NULL;
	
	int NumbersCount = 0;
	
	fInput  = fopen("cifra.in", "r");
	if (fInput == NULL)
		return 0;
	
	fOutput = fopen("cifra.out", "w");
	if (fOutput == NULL)
		return 0;
	
	fscanf(fInput, "%d", &NumbersCount);
	
	int NumberIndex = 0;
	for (NumberIndex = 0; NumberIndex < NumbersCount; NumberIndex++)
	{
		long CurrentNumber = 0;
		
		fscanf(fInput, "%ld", &CurrentNumber);
		
		int LastDigitForSum = power_mod(CurrentNumber);
		
		fprintf(fOutput, "%d \n", LastDigitForSum); 
	}
	
	fclose(fInput);
	fclose(fOutput);
	
	return 0;
}



#else
//RELEASE VERSION
//Release version - use precomputed table

unsigned char PrecomputedSums[PERIOD] = { 	0, 1, 5, 2, 8, 3, 9, 2, 8, 7,
											 7, 8, 4, 7, 3, 8, 4, 1, 5, 4,
											 4, 5, 9, 6, 2, 7, 3, 6, 2, 1,
											 1, 2, 8, 1, 7, 2, 8, 5, 9, 8, 
											 8, 9, 3, 0, 6, 1, 7, 0, 6, 5,
											 5, 6, 2, 5, 1, 6, 2, 9, 3, 2, 
											 2, 3, 7, 4, 0, 5, 1, 4, 0, 9, 
											 9, 0, 6, 9, 5, 0, 6, 3, 7, 6,
											 6, 7, 1, 8, 4, 9, 5, 8, 4, 3, 
											 3, 4, 0, 3, 9, 4, 0, 7, 1, 0,
										};		


int main()
{	
	FILE* fInput  = NULL;
	FILE* fOutput = NULL;
	
	int NumbersCount = 0;
	
	fInput  = fopen("cifra.in", "r");
	if (fInput == NULL)
		return 0;
	
	fOutput = fopen("cifra.out", "w");
	if (fOutput == NULL)
		return 0;
	
	fscanf(fInput, "%d", &NumbersCount);
	
	int NumberIndex = 0;
	for (NumberIndex = 0; NumberIndex < NumbersCount; NumberIndex++)
	{
		long CurrentNumber = 0;
		
		fscanf(fInput, "%ld", &CurrentNumber);
		
		int CurrentNumberLastTwoDigits = (CurrentNumber % PERIOD);
		int LastDigitForSum = PrecomputedSums[CurrentNumberLastTwoDigits];
		
		fprintf(fOutput, "%d \n", LastDigitForSum); 
	}
	
	fclose(fInput);
	fclose(fOutput);
	
	return 0;
}

#endif