Cod sursa(job #1291863)

Utilizator andreiudilaUdila Andrei andreiudila Data 13 decembrie 2014 13:52:32
Problema Factorial Scor 15
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.69 kb
#include <fstream>
using namespace std;
ifstream fin("fact.in");
ofstream fout ("fact.out");
int n,p,z[30],a[30],i,x,y;
int main()
{
    fin>>p;
    if(p==0) {fout<<1; return 0;}
    if(p==5) {fout<<-1; return 0;}
    if(p==1) {fout<<5; return 0;}
    a[1]=5;
    z[1]=1;
    n=1;
    while(z[n]+a[n]<p)
    {
        n++;
        z[n]=z[n-1]+a[n-1];
        a[n]=a[n-1]*5;
    }

    if(z[n]+a[n]==p) {fout<<n; return 0;}
    x=a[n];
    y=z[n];
    i=n-1;
    while(y<p && i>1)
    {
        y=y+(p-y)/z[i]*z[i];
        x=x+a[i]*((p-y)/z[i]);
        i--;
    }
    if(y==p) fout<<x;
    else if(i==1 && p-y<5) fout<<x+(p-y)*5;
    else fout<<-1;

    return 0;
}