Cod sursa(job #349505)

Utilizator grozaviorelGroza Viorel Mihai grozaviorel Data 19 septembrie 2009 22:02:00
Problema Factorial Scor 100
Compilator c Status done
Runda Arhiva de probleme Marime 2.24 kb
#include <stdio.h>
/*
P is a positive integer. Find the smalles positive integer N so that N! has exactly P zero (0) digit at the end.
We know that N! = 1 * 2 * 3 * .... * (N - 1) * N.
*/

//KEY POINT: The power of 5 in the decomposition of N! determines the number of zeros at the end

#define MAX_POWER5_INDEX 13
//Precomputed information
int PowerOf5[MAX_POWER5_INDEX + 1] = {			1,
												5,		  25,		  125,
											  625,		3125,	    15625,
											78125,	  390625,	  1953125,
										  9765625,	48828125,	244140625,
									   1220703125
									   };
									   
int ZerosCountForPowerOf5[MAX_POWER5_INDEX + 1] = {			0,
															1,		 6, 	   31,
														  156, 		781, 	 3906,
														19531, 	  97656,   488281,
													  2441406, 12207031, 61035156,
													305175781
													};

															

int GetFactorialWithTheNumberOfZerosAtEnd(int NumberOfZerosAtEnd)
{
	int Factorial = 0;
	
	int MaxPowerIndex = MAX_POWER5_INDEX;
	while (ZerosCountForPowerOf5[MaxPowerIndex] > NumberOfZerosAtEnd)
		MaxPowerIndex--;	//This will execute at least one time
		
	if (ZerosCountForPowerOf5[MaxPowerIndex] == NumberOfZerosAtEnd)
		Factorial = PowerOf5[MaxPowerIndex];
	else
	{
		int NumberOfZerosLeft = NumberOfZerosAtEnd;
		int PowerIndex = 0;
		for (PowerIndex = MaxPowerIndex; (PowerIndex > 0) && (NumberOfZerosLeft > 0); PowerIndex--)
		{
			int CrtPowerQuot = NumberOfZerosLeft / ZerosCountForPowerOf5[PowerIndex];
			NumberOfZerosLeft  = NumberOfZerosLeft % ZerosCountForPowerOf5[PowerIndex];
				
			if (CrtPowerQuot == 5)
			{
				Factorial = -1;
				break;
			}
			
			Factorial += (CrtPowerQuot * PowerOf5[PowerIndex]);
		} //end for
	}//end else
	
	return Factorial;
}


int main()
{	
	FILE* fInput  = NULL;
	FILE* fOutput = NULL;
	
	fInput  = fopen("fact.in", "r");
	if (fInput == NULL)
		return 0;
	
	fOutput = fopen("fact.out", "w");
	if (fOutput == NULL)
		return 0;

	int NumberOfZerosAtEnd = 0;
	fscanf(fInput, "%d", &NumberOfZerosAtEnd);
	
	int TheFactorialThatHaveZerosAtEnd = GetFactorialWithTheNumberOfZerosAtEnd(NumberOfZerosAtEnd);
	fprintf(fOutput, "%d", TheFactorialThatHaveZerosAtEnd);
	
	fclose(fInput);
	fclose(fOutput);
	
	return 0;
}