P1134 [USACO3.2]阶乘问题 题解

· · 个人记录

题意

太简洁明了,我就不写了。

给你一个数 n。让你求 n! 从右往左数第一个非零数是几。

思路

末尾 0 的来源是什么?是因子 2 与因子 5 相乘,得到 10。所以思路便浮出水面了:

先统计因子 2 与因子 5 的个数,然后得到 10 能配出多少个来,最后把配对剩下的 2 (因子 2 总是比因子 5 多,因为 2 在 n 以内的倍数比 5 多)与 [1,n] 中每一个数去除掉这两个因子后的积相乘, \bmod 10 即可。

这里拿样例举个例子:

\because 12!=12\times11...\times1

统计出含有总共 10 个因子 2,2 个因子 5,共能配对出 2 个 10,余下 2^8=256,再与[1,12] 中每一个数去除掉这两个因子后的积(设为 x) 相乘。最终答案为 256x\bmod10=6。

温馨提示

请边算边模,并建议您使用快速幂来算余下因子 2 的结果模 10。

上代码

#include <bits/stdc++.h>
using namespace std;
int n,ct2,ct5,ans=1,ff;
int ksm(int x,int y)
{
    int ret=1;
    if(y==0) return ret;
    while(y)
    {
        if(y&1)
        {
            ret=ret*x%10;
        }
        x=x*x%10;
        y>>=1;
    }
    return ret;
}
int main()
{
    //freopen("factorials.in","r",stdin);
    //freopen("factorials.out","w",stdout);
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int r1=i,r2=i,vt=i;
        while(r1%2==0)
        {
            r1/=2,++ct2;vt/=2;
        }
        while(r2%5==0)
        {
            r2/=5,++ct5;vt/=5;
        }
        ans=ans*vt%10;
    }
    //printf("%d %d\n",ct2,ct5);
    if(ct2>ct5) ff=ksm(2,(ct2-ct5));
    else ff=ksm(5,(ct5-ct2));
    //if(ct2==0||ct5==0) ff=1;
    //printf("%d %d\n",ans,ff);
    printf("%d",ans*ff%10);
    return 0;
}