Last digit
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3168 | Accepted: 966 |
Description
Determine the last nonzero digit in value of expression
.
Input
The input contains a single line with n and m separated by one or several spaces; n, m are natural numbers from 1 to 1000000, n ≥ m.
Output
The output contains a single line with the last nonzero digit.
Sample Input
4 2
Sample Output
6
题目题意:让你求该组合数的非0的末尾的数字.
题目分析:因为我们看到n和m的数值非常大,所以我们不可能直接利用公式求解。我们要想办法把这个分式化简。我们注意到任何数大于2的正整数到可以分解成素数的乘积,如果我们能把分数的分子和分母的公共质因子都划出,就减小很大了。
勒让德定律可以帮我们快速求出n!的质因子。
在正数n!的素因子标准分解式中,素数p的指数记作
接下来就是解决非0问题,很简单,应该只有5*2=10,末尾有0,所以我们成对的消除就行了。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e6+10;
int prime[maxn],cnt;
bool vis[maxn];
int ans[maxn][3];
void get_prime()//质数打表
{
memset (vis,true,sizeof (vis));
vis[1]=false;
for (int i=2;i<maxn;i++) {
if (vis[i]) prime[cnt++]=i;
for (int j=0;j<cnt&&i*prime[j]<maxn;j++) {
vis[i*prime[j]]=false;
if (i%prime[j]==0) break;
}
}
}
int get_sum(int p,int n)//勒让德定律,求出n!标准分解式中,素数P的指数
{
int ans=0;
while (n) {
ans+=n/p;
n=n/p;
}
return ans;
}
int fast_pow(int base,int k)//快速幂
{
int ans=1;
while (k) {
if (k&1)
ans=ans*base;
base=base*base;
k>>=1;
}
return ans;
}
int main()
{
get_prime();
int n,m;
while (scanf("%d%d",&n,&m)!=EOF) {
memset (ans,0,sizeof (ans));
for (int i=0;i<cnt&&prime[i]<=n;i++)//将n!分解
ans[i][0]=get_sum(prime[i],n);
for (int i=0;i<cnt&&prime[i]<=m;i++)//将m!分解
ans[i][1]=get_sum(prime[i],m);
for (int i=0;i<cnt&&prime[i]<=n-m;i++)//将(n-m)!分解
ans[i][2]=get_sum(prime[i],n-m);
for (int i=0;i<cnt&&prime[i]<=n;i++)//约掉公共质因子的指数
ans[i][0]-=(ans[i][1]+ans[i][2]);
if (ans[0][0]>ans[2][0]) {//处理非0,当2的指数大于5的指数时
ans[0][0]-=ans[2][0];
ans[2][0]=0;
}
else {//否则
ans[2][0]-=ans[0][0];
ans[0][0]=0;
}
int res=1;
for (int i=0;i<cnt&&prime[i]<=n;i++) {//挨个求,mod/10
if (ans[i][0]==0) continue;
res=res*fast_pow(prime[i],ans[i][0]);
res=res%10;
}
cout<<res<<endl;
}
return 0;
}