二分+质因数分解,LightOJ 1138Trailing Zeroes (III)

本文介绍了解决编程问题TrailingZeroes(III)的方法,通过计算1到n中5的因子数量确定阶乘中后缀零的数量,采用二分法寻找最小的N使得N!含有恰好Q个零。时间复杂度为O(log^2n),空间复杂度为O(1)。
摘要由CSDN通过智能技术生成

一、题目

1、题目描述

You task is to find minimal natural number N, so that N! contains exactly Q zeroes on the trail in decimal notation. As you know N! = 1 * 2 * ... * N. For example, 5! = 120, 120 contains one zero on the trail.

2、输入输出

2.1输入

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case contains an integer Q (1 ≤ Q ≤ 108) in a line.

2.2输出

For each case, print the case number and N. If no solution is found then print impossible.

3、原题链接

Trailing Zeroes (III) - LightOJ 1138 - Virtual Judge (vjudge.net)


二、解题报告

1、思路分析

对于一个阶乘我们如何计算出它有几个后缀0呢?

考虑到后缀0只能由2*5贡献得来,所以我们只需要计算出1~n能够拆出多少个2/5数对即可

又注意到可拆出的2的数目一定多于5的数目,故而我们求出因子5的数目就是2/5数对的数目

继而我们可以在O(logn)的时间内计算出n的阶乘有多少个后缀0

那么我们只需要二分答案,计算最小的满足的数字即可

2、复杂度

时间复杂度: O(log^2n)空间复杂度:O(1)

3、代码详解

#include <iostream>
#include <cstring>
using namespace std;
#define int long long
const int N = 1e7 + 10, mod = 1e9 + 7;
int n, f[N], res = 0;
void solve()
{
    cin >> n;
    for (int i = n; i >= 1; i--)
    {
        f[i] = ((n / i) * (n / i)) % mod;
        for (int j = i << 1; j <= n; j += i)
            f[i] = (f[i] - f[j] + mod) % mod;
        res = (res + f[i] * (i * i) % mod) % mod;
    }
    cout << res;
}
signed main()
{
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    //freopen("in.txt", "r", stdin);
    int _ = 1;
    while (_--)
        solve();
    return 0;
}

Sigma函数是指一个数字的所有因子之和。给定一个数字n,需要求出有多少个数字的Sigma函数是偶数。\[2\] 为了解决这个问题,可以先筛选出n范围内的素数(范围在10^6即可),然后对n进行素因子分解。对于每个因子,如果它的Sigma函数中连乘的每一项都是偶数,那么整个Sigma函数就是偶数。具体实现中,可以判断每个因子的平方根是否为偶数,如果是偶数,则减去(平方根+1)/2。\[1\] 另外,还可以使用O(1)的做法来解决这个问题。根据观察,所有的完全平方数及其两倍的值都会导致Sigma函数为偶数。因此,可以直接计算n的平方根,然后减去(平方根+1)/2即可得到结果。\[3\] #### 引用[.reference_title] - *1* [Sigma Function](https://blog.csdn.net/PNAN222/article/details/50938232)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [【LightOJ1336】Sigma Function(数论)](https://blog.csdn.net/qq_30974369/article/details/79009498)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

EQUINOX1

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

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

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

打赏作者

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

抵扣说明:

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

余额充值