Cod sursa(job #349191)

Utilizator grozaviorelGroza Viorel Mihai grozaviorel Data 18 septembrie 2009 16:04:25
Problema Cifra Scor 0
Compilator c Status done
Runda Arhiva de probleme Marime 2.33 kb
#include <stdio.h>
#include <mem.h>

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

#define PERIOD 100
#define MAX_DIGITS_COUNT 103

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,
										};		


//Return the number formed with the last two consecutive digits found in the string buffer
int GetLastTwoDigitDecimalNumberFromString(unsigned char* StrBuffer, int StrLen)
{
	//Get the last digit position
	int CharIndex = StrLen;
	while ( (CharIndex > 0)  && ((StrBuffer[CharIndex] < '0') || (StrBuffer[CharIndex] > '9')) )
		CharIndex--;

	unsigned char LastDigit = 0;
	if ( (StrBuffer[CharIndex] >= '0') && (StrBuffer[CharIndex] <= '9') )
		LastDigit = StrBuffer[CharIndex] - '0';
	
	unsigned char BeforeLastDigit = 0;
	if ( (CharIndex > 0) && (StrBuffer[CharIndex - 1] >= '0') && (StrBuffer[CharIndex - 1] <= '9') )
		BeforeLastDigit = StrBuffer[CharIndex - 1] - '0';
	
	int LastTwoDigitNumber = (BeforeLastDigit * 10) + LastDigit;
	
	return LastTwoDigitNumber;
}

int main()
{	
	FILE* fInput  = NULL;
	FILE* fOutput = NULL;
	
	fInput  = fopen("cifra.in", "r");
	if (fInput == NULL)
		return 0;
	
	fOutput = fopen("cifra.out", "w");
	if (fOutput == NULL)
		return 0;
	
	int NumbersCount = 0;
	fscanf(fInput, "%d", &NumbersCount);
	
	unsigned char buffer[MAX_DIGITS_COUNT + 1];
	
	//Just parse - skip the current line
	fgets(buffer, MAX_DIGITS_COUNT, fInput);
	
	int NumberIndex = 0;
	for (NumberIndex = 0; NumberIndex < NumbersCount; NumberIndex++)
	{
		//Reset buffer - set to new line character
		memset(buffer, '\n', MAX_DIGITS_COUNT + 1);
		
		fgets(buffer, MAX_DIGITS_COUNT, fInput);
		
		int CurrentNumberLastTwoDigits = GetLastTwoDigitDecimalNumberFromString(buffer, MAX_DIGITS_COUNT);
		
		int LastDigitForSum = (int)(PrecomputedSums[CurrentNumberLastTwoDigits]);
		
		fprintf(fOutput, "%d\n", LastDigitForSum); 
	}
	
	fclose(fInput);
	fclose(fOutput);
	
	return 0;
}