Skip to content

gh-160050: Use asymptotically faster divmod in l_mod for large integers - #160443

Open
emirplus wants to merge 2 commits into
python:mainfrom
emirplus:gh-160050-fast-modulo-huge-ints
Open

emirplus wants to merge 2 commits into
python:mainfrom
emirplus:gh-160050-fast-modulo-huge-ints

Conversation

@emirplus

@emirplus emirplus commented Oct 23, 2026 •

Copy link
Copy Markdown

Fixes #160050.

In Objects/longobject.c, l_divmod switches to pylong_int_divmod() when operands exceed the threshold (size_w > 300 && (size_v - size_w) > 150), providing asymptotically faster division. However, l_mod() bypassed this fast path and fell through directly to long_rem(), resulting in integer modulo (%) taking significantly longer than divmod(a, b)[1] for large integers.

This patch adds the same WITH_PYLONG_MODULE threshold check in l_mod(), invoking pylong_int_divmod(v, w, NULL, pmod) when sizes exceed the threshold.

Benchmark

Using the benchmark from the issue with operands where bits = 128_000:

  • Before: // = 0.0105s, % = 0.0224s, divmod = 0.0083s (modulo ~2.1x slower than integer division)
  • After: // = 0.0088s, % = 0.0093s, divmod = 0.0098s (modulo has matching complexity)

Testing

  • Added test_pylong_int_mod in Lib/test/test_int.py.
  • Extended test_pylong_int_divmod_crash to cover %.
  • Verified all tests pass with ./PCbuild/amd64/python.exe -m test test_int test_long.

@python-cla-bot

python-cla-bot Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

Comment thread Objects/longobject.c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

modulo for huge integers has the wrong complexity

2 participants