NEFU 118 n!后面有多少个0 (小结论)

版权声明:转载注明下出处就行了。 https://blog.csdn.net/LJD201724114126/article/details/89109584

题目链接:哆啦A梦传送门

题意: 找出n!有多少个0?

题解:只有质因子2与质因子5相乘后末尾才会出现0。

例如:100 是由 2*2*5*5。

故我们只需找出有多少个质因子2的个数与质因子5的个数,其实只需找质因子5的个数就好了,因为质因子2出现的次数一定比质因子5出现的次数多。

找出质因子5的个数x=N/5+N/(5*5)+...

 N/5表示不大于N的数中能被5整除的数贡献一个5,N/(5*5)表示不大于N的数中能被25整除的数再贡献一个5…….

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;


int main()
{

    int ncase;
    scanf("%d",&ncase);

    LL n;
    while(ncase--)
    {
        scanf("%lld",&n);

        int x=0,y=0;

        LL sum=1;

        while(n/(sum*=2))
        {
            x+=n/sum;
        }

        sum=1;

        while(n/(sum*=5)){
            y+=n/sum;
        }

        printf("%d\n",min(x,y));
    }

    return 0;

}

用下面的 方法也能找,但会溢出。


#include <bits/stdc++.h>
using namespace std;

typedef long long LL;


int main(){



    int ncase;
    scanf("%d",&ncase);

    LL n;
    while(ncase--)
    {
        scanf("%lld",&n);

        LL x=0; LL y=0;
        LL item=1;
        for(LL i=1;i<=n;i++){

                item*=i;

        while(item%2==0)
        {
            item/=2;
            x++;
        }



        while(item%5==0){
            item/=5;
            y++;
        }
//printf("item=%lld\n",item);
        }

        printf("x=%lld,y=%lld\n",x,y);

        printf("%lld\n",min(x,y));
    }

    return 0;

}










猜你喜欢

转载自blog.csdn.net/LJD201724114126/article/details/89109584
118