Trailing Zeroes (III)

来源:互联网 发布:华为java面试题2016 编辑:程序博客网 时间:2024/06/06 03:18

点击打开链接

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.

Input


Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case contains an integer Q (1 ≤ Q ≤ 108) in a line.

Output


For each case, print the case number and N. If no solution is found then print 'impossible'.

Sample Input


3

1

2

5

Sample Output


Case 1: 5

Case 2: 10

Case 3: impossible

阶乘末尾一个零表示一个进位,则相当于乘以10

而10 是由2*5所得,在1~100当中,可以产生10的有:0 2 4 5 6 8 结尾的数字,

显然2是足够的,因为4、6、8当中都含有因子2,所以都可看当是2,那么关键在于5的数量了

那么该问题的实质是要求出1~100含有多少个5

由特殊推广到一般的论证过程可得:

每隔5个,会产生一个0,比如 5, 10 ,15,20.。。 

每隔 5×5 个会多产生出一个0,比如 25,50,75,100 

每隔 5×5×5 会多出一个0,比如125.

所以100!末尾有多少个零为:

100/5+100/25=20+4=24

那么1000!末尾有多少个零呢?同理得:

1000/5+1000/25+1000/125=200+40+8=248

到此,问题解决了,但我们在学习过程中应当学会发散思维、举一反三

接着,请问N!的末尾有多少个零呢??

其实 也是同理的

N/5+N/25+……

#include<cstdio>#include<algorithm>#define max 1000000000000using namespace std;long long num(long long n){int ans=0;while(n){ans+=n/5;n/=5;}return ans;}int main(){int t;long long n;int i=1;scanf("%d",&t);while(t--){scanf("%lld",&n);int left=1;long long right=max;int flag=0;printf("Case %d: ",i);i++;while(left<=right){int mid=(left+right)/2;if(num(mid)==n){flag=mid;right=mid-1;}else if(num(mid)>n)right=mid-1;elseleft=mid+1;}if(flag)printf("%lld\n",flag);elseprintf("impossible\n");} return 0;}


原创粉丝点击