Divmod And Floor Division With Negatives
Compute quotients and remainders with //, %, and divmod: Python floors toward negative infinity, so negative operands still satisfy q*b+r==a.
Code
# 负数地板除: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})")Output
Captured from a sandboxed run of this snippet in the build pipeline.
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)How it works
Repetition is confined to for a, b in [(57, 10), (-57, 10), (57, -10), (-57, -10)] — the rest of the file is straight-line.
Points of care
- Everything comes from the standard library, so copying it in just works.
Using it
The demo output is labeled (7 // 2 =, -7 // 2 =, divmod(57, 10) ->), and every line carries the name of its operation.
Key statements
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})")
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared.
Report a problem with this exampleOpens a pre-filled issue on GitHub.