LightOJ1138 —— 阶乘末尾0、质因子分解

题目链接:https://vjudge.net/problem/LightOJ-1138

1138 - Trailing Zeroes (III)
Time Limit: 2 second(s) Memory Limit: 32 MB

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

Output for Sample Input

3

1

2

5

Case 1: 5

Case 2: 10

Case 3: impossible

题意:

求是否存在一个数n,使得 n! 的十进制表示末尾有Q个0,如存在,输出最小值。

题解:

1. 对 n! 进行质因子分解:n! = 2^a1 * 3^a2 * 5^a3 * …… 。

2.可知质因子2出现的次数大于质因子5出现的次数,且质因子中只有2*5 = 10。综上,有多少个质因子5,末尾就有多少个0。

3.那怎么知道 n! 里面有多少个质因子5呢? 

答: 从1到n,有多少个数是5的倍数呢? n/5 个。 当这n/5数格子除以5之后,又还剩几个数是5的倍数呢? 那就是 (n/5)/5 个,然后一直下去。

代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <vector>
 6 #include <cmath>
 7 #include <queue>
 8 #include <stack>
 9 #include <map>
10 #include <string>
11 #include <set>
12 using namespace std;
13 typedef long long LL;
14 const int INF = 2e9;
15 const LL LNF = 9e18;
16 const int MOD = 1e9+7;
17 const int MAXN = 1e6+10;
18 
19 LL Count(LL tmp)
20 {
21     LL sum = 0;     //不能定义int
22     while(tmp) sum += tmp/5, tmp /= 5;
23     return sum;
24 }
25 
26 int main()
27 {
28     int T, kase = 0;
29     scanf("%d", &T);
30     while(T--)
31     {
32         LL Q;
33         scanf("%lld", &Q);
34         LL l = 0, r = LNF;
35         while(l<=r)
36         {
37             LL mid = (l+r)/2;
38             if(Count(mid)>=Q)
39                 r = mid - 1;
40             else
41                 l = mid + 1;
42         }
43 
44         printf("Case %d: ", ++kase);
45         if(Count(l)!=Q)
46             printf("impossible
");
47         else
48             printf("%lld
", l);
49     }
50 }
View Code
原文地址:https://www.cnblogs.com/DOLFAMINGO/p/8377310.html