Cod sursa(job #331296)

Utilizator GagosGagos Radu Vasile Gagos Data 13 iulie 2009 16:26:04
Problema Factorial Scor 85
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.14 kb
#include<cstdio>

using namespace std;

long long i, pow5_p[14], pow5[14], p, sol = 1, p1, sol1, sol2;

long binary_search(long val)
{
	long j, step;
	
	for(step = 1; step < 12; step <<= 1);
	for(j = 1; step; step >>= 1)
		if(j + step < 12 && pow5_p[j + step] <= val)
			j += step;
	
	return j;
}

int main()
{
	freopen("fact.in","r",stdin);
	freopen("fact.out","w",stdout);
	
	scanf("%lld", &p);
	
	if(p == 0)
	{
		printf("1\n");
		return 0;
	}
	pow5[0] = 1;
	for(i = 1; i <= 12; ++i)
	{
		pow5_p[i] = pow5_p[i - 1] + sol;
		sol *= 5;
		pow5[i] = sol;
	}
	sol = 0;
	p1 = p;
	while(p1)
	{
		sol += pow5[binary_search(p1)];
		p1 -= pow5_p[binary_search(p1)];
	}
	p1 = p;
	while(p1)
	{
		sol1 += pow5[binary_search(p1)];
		p1 -= pow5_p[binary_search(p1)];
		sol2 = sol - sol1;
		for(i = 1;i <= 12; ++i)
			if(sol2 == pow5[i])
				if(pow5_p[binary_search(p1)] < pow5_p[i])
				{
					printf("-1\n");
					return 0;
				}
	}
	for(i = 1;i <= 12; ++i)
		if(sol == pow5[i])
			if(pow5_p[binary_search(p)] < pow5_p[i])
			{
				printf("-1\n");
				return 0;
			}
	
	printf("%lld\n", sol);
	
	return 0;
}