NYOJ -216 A problem is easy
发布日期:2025-04-22 12:45:48 浏览次数:4 分类:精选文章

本文共 1788 字,大约阅读时间需要 5 分钟。

为了解决这个问题,我们需要找到满足条件的整数对 (i, j) 的数量,使得 N = i * j + i + j,其中 0 < i ≤ j。

方法思路

我们可以将问题转化为数学公式: N = i * j + i + j 可以改写为: N + 1 = (i + 1) * (j + 1)

这意味着我们需要找到 N + 1 的所有因数对 (a, b),其中 a ≤ b 且 a 和 b 都是至少 2 的整数。因此,问题转化为计算 N + 1 的因数数目,并统计其中满足条件的因数对数目。

具体步骤如下:

  • 计算 M = N + 1。
  • 分解 M 的质因数。
  • 生成所有因数。
  • 统计满足条件的因数对数目。
  • 解决代码

    import math
    def factorize(M):
    factors = {}
    while M % 2 == 0:
    factors[2] = factors.get(2, 0) + 1
    M = M // 2
    i = 3
    while i * i <= M:
    while M % i == 0:
    factors[i] = factors.get(i, 0) + 1
    M = M // i
    i += 2
    if M > 1:
    factors[M] = 1
    return factors
    def generate_factors(factors):
    factor_list = list(factors.items())
    factors = [1]
    for (p, exp) in factor_list:
    temp = []
    for d in factors:
    current = d
    for e in range(exp + 1):
    temp.append(current)
    current *= p
    factors = list(set(temp))
    return sorted(factors)
    def count_valid_factors(factors, M):
    sqrt_m = math.isqrt(M)
    count = 0
    for f in factors:
    if f >= 2 and f <= sqrt_m:
    count += 1
    return count
    def main():
    import sys
    input = sys.stdin.read().split()
    T = int(input[0])
    for i in range(1, T + 1):
    N = int(input[i])
    M = N + 1
    if M == 1:
    print("00")
    continue
    factors = factorize(M)
    factors_list = generate_factors(factors)
    count = count_valid_factors(factors_list, M)
    print(f"{count:02d}")
    if __name__ == "__main__":
    main()

    代码解释

  • factorize 函数:用于分解给定的整数 M 的质因数,并返回一个字典,其中键为质因数,值为对应的指数。
  • generate_factors 函数:根据质因数分解结果生成所有因数。
  • count_valid_factors 函数:统计满足条件的因数对数目。
  • main 函数:读取输入,处理每个测试用例,计算结果并输出。
  • 该方法通过质因数分解高效地计算因数数目,确保在大数据范围内也能快速解决问题。

    上一篇:NYOJ 1066 CO-PRIME(数论)
    下一篇:ny540 奇怪的排序 简单题

    发表评论

    最新留言

    表示我来过!
    [***.240.166.169]2025年04月03日 19时29分00秒

    关于作者

        喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
    -- 愿君每日到此一游!

    推荐文章