Problem Link : http://lightoj.com/volume_showproblem.php?problem=1138
Solution idea : binary search problem..take any number and find how many trailing zeros are in it...compare it with required number and continue the process.
Solution :
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll int fact ( ll int n,ll int p )
{
ll int x = n;
ll int freq = 0;
while ( x / p )
{
freq += x / p;
x = x / p;
}
return freq;
}
ll int func(ll int n)
{
ll int hi=1000000000000000000,lo=0,mid,ans,a1,a2,w=-1;
while(lo<=hi)
{
mid=(lo+hi)/2;
a1=fact(mid,2);
a2=fact(mid,5);
a1=min(a1,a2);
if(a1==n)
{
hi=mid-1;
ans=mid;
w=0;
}
else if(a1>n)
{
hi=mid-1;
}
else lo=mid+1;
}
if(w==0) return ans;
else return -1;
}
int main()
{
ll int t,n,ans;
scanf("%lld",&t);
for(ll int ca=1; ca<=t; ca++)
{
scanf("%lld",&n);
ans=func(n);
if(ans==-1) printf("Case %lld: impossible\n",ca);
else printf("Case %lld: %lld\n",ca,ans);
}
}
Solution idea : binary search problem..take any number and find how many trailing zeros are in it...compare it with required number and continue the process.
Solution :
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll int fact ( ll int n,ll int p )
{
ll int x = n;
ll int freq = 0;
while ( x / p )
{
freq += x / p;
x = x / p;
}
return freq;
}
ll int func(ll int n)
{
ll int hi=1000000000000000000,lo=0,mid,ans,a1,a2,w=-1;
while(lo<=hi)
{
mid=(lo+hi)/2;
a1=fact(mid,2);
a2=fact(mid,5);
a1=min(a1,a2);
if(a1==n)
{
hi=mid-1;
ans=mid;
w=0;
}
else if(a1>n)
{
hi=mid-1;
}
else lo=mid+1;
}
if(w==0) return ans;
else return -1;
}
int main()
{
ll int t,n,ans;
scanf("%lld",&t);
for(ll int ca=1; ca<=t; ca++)
{
scanf("%lld",&n);
ans=func(n);
if(ans==-1) printf("Case %lld: impossible\n",ca);
else printf("Case %lld: %lld\n",ca,ans);
}
}
No comments:
Post a Comment