You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现两个整数列表对应元素相除并输出最简分数的方法

你可以直接通过整数最大公约数(GCD)对分子分母做约分,全程不涉及浮点数运算,完全避免精度损失,哪怕是超大整数也能正确处理。

实现代码

import math

a = [6198089008491993412800, 3099044504245996706400, 2066029669497331137600, 2324283378184497529800, 1239617801698398682560, 2066029669497331137600, 1328161930391141445600, 1549522252122998353200, 1033014834748665568800, 1549522252122998353200]
b = [3099044504245996706400, 2066029669497331137600, 2324283378184497529800, 1239617801698398682560, 2066029669497331137600, 1328161930391141445600, 1549522252122998353200, 1033014834748665568800, 1549522252122998353200, 1126925274271271529600]

# 生成最简分数列表
c = []
for numerator, denominator in zip(b, a):
    common_divisor = math.gcd(numerator, denominator)
    reduced_num = numerator // common_divisor
    reduced_den = denominator // common_divisor
    c.append(f"{reduced_num}/{reduced_den}")

# 按要求格式输出
print(", ".join(c))

运行后输出结果和你预期的完全一致:

1/2, 2/3, 9/8, 8/15, 5/3, 9/14, 7/6, 2/3, 3/2, 8/11

兼容说明

如果你使用的Python版本低于3.5,或者需要处理负数场景,可以自定义实现GCD函数替换math.gcd:

def calc_gcd(x, y):
    while y:
        x, y = y, x % y
    return abs(x)

内容的提问来源于stack exchange,提问作者Jerry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 08:09:03