poj 1150 The Last Non-zero Digit(阶乘取模运算的简单性质及递归技巧)

本文介绍一种高效算法来求解n!尾部的最后一个非零数字。通过分析阶乘序列中不同质数的幂次贡献,利用递归方法计算特定质数的出现次数,并结合奇数列末尾特定数字的出现规律,最终得出解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

The Last Non-zero Digit

题目分析

参见http://www.cppblog.com/abilitytao/archive/2009/10/31/99907.html
题解写的非常好.我就简要总结一下自己的收获.对于n!分解成一个数x的幂次我们可以递归的去计算.因为只有x的倍数相乘才会产生x的幂次.及 x,x2,x3,, 因此

f(n,x)=f(n/x,x)+n/x

求解这种问题其实是把阶乘序列分解成某些数的倍数.然再用除去这个倍数依然是阶乘的方法进行递归计算.详细题解见参考.

AC code

#include<iostream>
#include<string>
#include<iomanip>
#include<algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <cstdio>
using namespace std;

#define MAXN 9999
#define MAXSIZE 100
#define DLEN 4

typedef long long LL;
const int maxn = 100+10;

int n,m;

LL num2,num5,num3,num7,num9;

LL prime_num(int n,int p){//计算n!中素数p出现的幂次.(素数并不是必须的)
    if(n==0)return 0;
    else return n/p+prime_num(n/p,p);
}
LL odd_num(int n,int x){//计算奇数列末尾x出现的次数.3,7,9
    return n==0?0:n/10+(n%10>=x)+odd_num(n/5,x);
}

LL fact_num(int n,int x){//n!中x出现的次数
    return n==0?0:fact_num(n/2,x)+odd_num(n,x);
}

int table[4][4] = {
    6,2,4,8,
    1,3,9,7,
    1,7,9,3,
    1,9,1,9,
};


int main(int argc, char const *argv[]) {


    while (scanf("%d%d",&n,&m )!=EOF) {
        num2 = prime_num(n,2)-prime_num(n-m,2);
        num5 = prime_num(n,5)-prime_num(n-m,5);
        num3 = fact_num(n,3)-fact_num(n-m,3);
        num7 = fact_num(n,7)-fact_num(n-m,7);
        num9 = fact_num(n,9)-fact_num(n-m,9);

        //std::cout << num2 <<" "<<num3<<" "<<num5<<" "<<num7<<" "<<num9<< '\n';
        LL res =1;
        if(num2<num5){
            std::cout << "5" << '\n';
        }else{
            if(num2>num5){
                res = res*table[0][(num2-num5)%4]%10;
            }
            res = res*table[1][num3%4]%10;
            res = res*table[2][num7%4]%10;
            res = res*table[3][num9%4]%10;
            std::cout << res << '\n';
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值