Repository navigation
Conversation
calculatePerm multiplied the k factors one at a time into a growing product, so each step was a big-by-small multiplication and the whole loop was quadratic in the result size. math.perm(615913, 286885) took about 28 s on a JVM build against about 1 s on CPython. Splitting the range in halves keeps the operands of each multiplication balanced, so BigInteger can use its faster algorithms; the same call now takes 0.3 s. Signed-off-by: Jeongseop Lim <jeongseop_lim@korea.ac.kr>
jseop-lim
force-pushed
the
fix/math-perm
branch
from
October 31, 2026 11:51
e10ec09 to
d99ac7a
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Fixes #1254
math.perm(n, k)multiplied the running product by one factor at a time, so its cost grew with the square of the result size andBigInteger.multiplynever got two large operands. CPython splits the product asP(n, k) = P(n, j) * P(n - j, k - j)withj = k / 2(mathmodule.c#L3634-L3649), so the large multiplications are between operands of similar size.AS-IS
TO-BE
Timings for
math.perm(615913, 286885)on macOS arm64:mx python-jvm(interpreted JVM)mx python-jvm(interpreted JVM)Changes
P(n, k)inPermNodeby recursive halving instead of the sequential loop.test_perm_matches_productin a newtests/test_math_perm.py.Testing
mx python-jvmon darwin-aarch64, then--tagged test_math(79 passed, same as master). The new test passes before and after the change; it checks values, not time.math.perm(n, k)equalsfactorial(n) // factorial(n - k)for everyn < 60and everyk.