Trailing Zeroes (III) LightOJ

来源:互联网 发布:网络客服流程图 编辑:程序博客网 时间:2024/06/05 22:38

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

首先可以发现有规律,每当出现5的倍数的时候就会出现0,因为它前面肯定有2的倍数。

正规题解:
根据算术基本定理,可以得到x = 2 ^ a *3^b*5^c....
只有当2 和 5 出现的时候才能出想0,因为2 的个数肯定比5多,所以对于每个5,都能使结果多一个0。于是只要求到n! 中有多少个5 个数,但是对于n! 来讲,无法直接求到它的值,需要通过一些方法来解决;

用到了一个数论知识:
若p是质数,p<=n,则n!是p的倍数,设p^x是p在n!内的最高幂,则
x=[n/p]+[n/p^2]+[n/p^3]+…………;
而且[n/(ab)]=[[n/a]/b];

转自

#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<queue>#include<algorithm>#define ll long long#define inf 0x3f3f3f3f#define maxn 1000007  // 1e6+7using namespace std;int solve(ll n)  // 找出 1 到  n 有多少个 5 。根据数论知识 {               ll ans = 0;    while( n )      {        ans += n / 5;         n /= 5;    }    return ans;}int find(ll n){    ll l = 1;    ll r = 1e12;    ll ans = -1;    ll mid;    while( l <= r)    {        mid = ( l + r) / 2;        int tmp = solve( mid );        if  ( tmp < n)            {                l = mid + 1;            }        else if( tmp == n)            {                ans = mid;                r = mid - 1;             }        else if( tmp > n)            r = mid - 1;    }    return ans;}int main(){    int t;    ll n;    scanf("%d",&t);    for(int i = 1; i <= t; i ++)    {        scanf("%lld",&n);        ll ans = find(n);        if( ans == -1)            printf("Case %d: impossible\n",i);        else printf("Case %d: %lld\n",i,ans);    }    return 0;}
0 0
原创粉丝点击