poj 3406 (勒让德定理)

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, nm.

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;
}




                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值