← 中文资源

简体中文版本

divmod 与负数地板除

负数参与 // 与 % 时 Python 向负无穷取整,与 C 风格截断不同;divmod 一次拿到商和余数,q*b+r==a 的不变式在四种符号组合下都成立。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

7 // 2  = 3 | 7 % 2 = 1
-7 // 2 = -4 | -7 % 2 = 1
7 // -2  = -4 | 7 % -2 = -1
divmod(57, 10) -> (5, 7)
pages needed: 6
divmod(57, 10) = (5, 7)
divmod(-57, 10) = (-6, 3)
divmod(57, -10) = (-6, -3)
divmod(-57, -10) = (5, -7)

实现说明

这个文件只在 for a, b in [(57, 10), (-57, 10), (57, -10), (-57, -10)] 里循环。

使用要点

  • 直接运行文件,输出会带上标签,比如 7 // 2 =、-7 // 2 =、divmod(57, 10) ->——输出的每一行都能指回产生它的那次调用。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。

核心语句

for a, b in [(57, 10), (-57, 10), (57, -10), (-57, -10)]:
    q, r = divmod(a, b)
    assert q * b + r == a and abs(r) < abs(b) and (r == 0 or (r > 0) == (b > 0))
    print(f"divmod({a}, {b}) = ({q}, {r})")

代码示例

# 负数地板除:Python 的 // 与 % 向负无穷取整,与 C/Java 的截断语义不同
print("7 // 2  =", 7 // 2, "| 7 % 2 =", 7 % 2)
print("-7 // 2 =", -7 // 2, "| -7 % 2 =", -7 % 2)
print("7 // -2  =", 7 // -2, "| 7 % -2 =", 7 % -2)

# divmod 一次拿到商和余数:分页、分批时少一次乘减
pages, remainder = divmod(57, 10)
print("divmod(57, 10) ->", (pages, remainder))
print("pages needed:", pages + (1 if remainder else 0))

# 不变式:q*b + r == a,余数与除数同号且 |r| < |b|,四种符号组合都成立
for a, b in [(57, 10), (-57, 10), (57, -10), (-57, -10)]:
    q, r = divmod(a, b)
    assert q * b + r == a and abs(r) < abs(b) and (r == 0 or (r > 0) == (b > 0))
    print(f"divmod({a}, {b}) = ({q}, {r})")