求阶乘结果末尾有几个0(求5因子的数量)

题目

#include<bits/stdc++.h>
using namespace std;
#define int __int128
int qpow(int a, int b){
    int res = 1; 
    while(b){
        if(b & 1) res = res * a;
        a = a * a;
        b >>= 1;
    }
    return res;
}
inline __int128 read(){
    __int128 x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x*f;
}
inline void write(__int128 x){
    if(x<0){
        putchar('-');
        x=-x;
    }
    if(x>9)
        write(x/10);
    putchar(x%10+'0');
}
signed main(){
    int n, i, j, k = 0;
    n = read();
    int now = 1;
    while(now < n){
        now *= 5;
        k++;
    }
    int res = 0, res_even = 0, c = 1;
    for(i = 1; i <= k; i++){
        c *= 5;
        if(c > n) break;
        int x = n / c;
        if(x == 0) break;
        int tmp = x;
        int cnt = n - n / c * c + 1;
        res += c * (x - 1) * x / 2 + cnt * x;
        if(x % 2 == 0){
            res_even += (c / 2) * (x / 2 * x / 2);//不能写成(x * x / 4)!!!因为如果不能整除的话可能会出错,也不能写成(c / 2) * x / 2 * x / 2,后面是一个整体,得加括号
            res_even += ((c + 1) / 2) * ((x - 1) / 2 * x / 2);//同理
            res_even += (cnt + 1) / 2 * x;
        } 
        else{
            res_even += c / 2 * ((x - 1) / 2 * (x - 1) / 2);     
            res_even += (c + 1) / 2 * ((x - 1) / 2 * (x + 1) / 2);
            res_even += (cnt) / 2 * x;
        }
    }
    if(n % 2 == 0) write(res_even);
    else write(res - res_even);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__night_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值