阶乘尾数0的个数

题目:http://tonylin.top/Conpro/read/pid/1048/cid/100060

给出q,求最小的n满足n!的末尾零个数为q

Input:

输入第一行为一个整数T(1 <= T <= 1000),表示测试数据有T组
2~T+1行 每行包含一个整数q(1 <= q <= 1e8),代表一组测试数据
 

Output:

对于每组测试数据,按照样例格式输出case number和n,如果没有可行解则输出"impossible"(不包含引号)

Sample Input:

3
1
2
5

Sample Output:

Case 1: 5
Case 2: 10
Case 3: impossible

思路:先写出函输求n!的尾数0个数,每个5的倍数贡献一个0,但是25贡献2个,125贡献3个。用二分法找一定范围内的整数的尾数个数等于q的情况。
代码:
#include<stdio.h>
#define ll long long
ll q,n,t,s,h;

ll finda(ll x)///求x!的尾数的0的个数
{
    ll num=0;
    while(x/5!=0)
    {
        x=x/5;
        num=num+x;
    }
    return num;
}

ll fen(ll s,ll h,ll q)///二分法查找
{
    ll m=(s+h)/2;
    if( finda(m)==q ) return m;
    else if( s==h ) return 0;///找到最后还找不到,另一个出口
    else if( finda(m)<q ) return fen( m+1,h,q );
    else return fen( s,m,q );///正宗二分法,s~m和m+1~h
}

int main()///1048
{
    int cnt=0;
    scanf("%lld",&t);
    while(t--)
    {
        scanf("%lld",&q);
        s=1;
        h=500000000;
        n=fen(s,h,q);
        if( n==0 )
            printf("Case %d: impossible\n",++cnt);
        else
        {
            if(n%5==0)
                printf("Case %d: %lld\n",++cnt,n);
            else
                for(int i=1;i<=4;i++)
                if( (n-i)%5==0 )
                {
                    printf("Case %d: %lld\n",++cnt,n-i);
                    break;
                }
        }
    }
    return 0;
}
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/shoulinniao/p/9499478.html