Cod sursa(job #1558861)

Utilizator daniel.sanduSandu Daniel daniel.sandu Data 29 decembrie 2015 18:08:41
Problema Factorial Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.99 kb
#include <fstream>
#include <cstdio>

int getFiveFactors(int x) {
	int count = 0;
	for ( ; x % 5 == 0; ++count, x /= 5)
		continue;
	return count;
}

int getFiveFactorCount(int n) {
	int count = 0;
	while (n && n % 5) --n;
	for ( ; n > 0; n -= 5)
		count += getFiveFactors(n);
	return count;
}

int factorial(int p) {
	unsigned position = 1, offset = 0, best = -1;
	if (p == 0)
		return position;
	for (offset = 1; offset < 5 * p; offset <<= 1)
		continue;

	for (offset >>= 1; offset; offset >>= 1) {
		int zeros = getFiveFactorCount(position + offset);
		if (zeros == p)
			best = position + offset;
		else if (p > zeros)
			position += offset;
  }
	if (getFiveFactorCount(position) == p)
		return position;
	return best;
}

int main() {
	char const * const inputFile = "fact.in",
						 * const outputFile = "fact.out";
	std::ifstream in(inputFile);
	std::ofstream out(outputFile);

	int p = 0;
	while (in >> p)
		out << factorial(p) << std::endl;
	return 0;
}