Cod sursa(job #332052)

Utilizator GagosGagos Radu Vasile Gagos Data 16 iulie 2009 13:13:45
Problema Factorial Scor 85
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.58 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 < 13; 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 <= 13; ++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 <= 13; ++i)  
            if(sol2 == pow5[i])  
                if(pow5_p[binary_search(p1)] < pow5_p[i])  
                {
	 sol = -1;
	 break;   
                }  
    }
    if(sol != -1)
    {  
        for(i = 1;i <= 13; ++i)  
            if(sol == pow5[i])  
                if(pow5_p[binary_search(p)] < pow5_p[i])  
                {  
                    sol = -1;  
                    break;  
                }
    }  
      
    printf("%lld\n", sol);  
      
    return 0;  
}