Trailing Zeroes (III) LightOJ - 1138
You task is to find minimal natural number N, so that N! contains exactly Q zeroes on the trail in decimal notation. As you know N! = 1*2*...*N. For example, 5! = 120, 120 contains one zero on the trail.
InputInput starts with an integer T (≤ 10000), denoting the number of test cases.
Each case contains an integer Q (1 ≤ Q ≤ 108) in a line.
For each case, print the case number and N. If no solution is found then print 'impossible'.
3
1
2
5
Case 1: 5
Case 2: 10
Case 3: impossible
题意:找到一个最小的自然数,使得其阶乘的末尾连续的0的个数为Q个。
思路:找规律,不要试图求出阶乘。
规律:例:从1!到4!,末尾无0;5!到9!,末尾1个0;10!到14!,末尾2个0;
可发现5的倍数如5、10、15、20、25等等,都会提供1个0,25的倍数如25、50、75等等,都会加2个0,125的倍数如125、250等等会加3个0 .....往后以此类推。
方法:运用二分法,就是把mid当做答案验证,看看mid的阶乘后面的0,是不是Q个。
如何判断:例:mid=100
-
mid/5,看mid中有几个5,有25个,意味着5、10、15、20.....提供了25个0
-
mid/25,看mid中有几个25,有4个,意味着25、50、75、100会提供8个0,但第一步这4个数已经提供了4个0,故这一步提供了4个0
-
mid/125,发现除不了,则结束了,一共提供了 29个0 故,答案为29
从上可发现,十分巧妙,只要求出有几个5,几个25,几个125,几个小于mid的5的次方,加起来就是答案。
#include<stdio.h>
int main()
{
int t,z,ans,e;
int mid,l,r,x;
while(~scanf("%d",&t))
{
e=1;
while(t--)
{
scanf("%d",&z);
l=1,r=5e8,mid=(l+r)/2;
while(l!=mid)
{
ans=0;
x=mid;
while(x!=0)
{
ans+=x/5;
x/=5;
}
if( ans >= z)
r=mid;
else l=mid;
mid = (l + r) / 2;
}
ans=0;
x=mid+1;
while(x!=0)
{
ans+=x/5;
x/=5;
}
printf("Case %d: ",e++);
if(ans==z)
printf("%d\n",mid+1);
else printf("impossible\n");
}
}
return 0;
}
#include<stdio.h>
int main()
{
int t,z,ans,e;
int mid,l,r,x;
while(~scanf("%d",&t))
{
e=1;
while(t--)
{
scanf("%d",&z);
l=1,r=5e8,mid=(l+r)/2;
while(l!=mid)
{
ans=0;
x=mid;
while(x!=0)
{
ans+=x/5;
x/=5;
}
if( ans >= z)
r=mid;
else l=mid;
mid = (l + r) / 2;
}
ans=0;
x=mid+1;
while(x!=0)
{
ans+=x/5;
x/=5;
}
printf("Case %d: ",e++);
if(ans==z)
printf("%d\n",mid+1);
else printf("impossible\n");
}
}
return 0;
}