跳到正文

个人记录

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

AsoltA约 2 分钟
原文
文章信息与版本

文章信息

发布
2022年10月21日
收录
2026年8月20日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前

题意

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

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

思路

末尾 00 的来源是什么?是因子 22 与因子 55 相乘,得到 1010。所以思路便浮出水面了:

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

这里拿样例举个例子:

∵12!=12×11...×1\because 12!=12\times11...\times1

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

温馨提示

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

上代码

C++
#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;
}
原文