Skip to content

fmpz_mod_ctx: only test the modulus for primality when needed - #457

Open
KainanP wants to merge 1 commit into
flintlib:mainfrom
KainanP:fmpz-mod-ctx-lazy-is-prime
Open

KainanP wants to merge 1 commit into
flintlib:mainfrom
KainanP:fmpz-mod-ctx-lazy-is-prime

Conversation

@KainanP

@KainanP KainanP commented Nov 29, 2026

Copy link
Copy Markdown

Fixes #333.

fmpz_mod_ctx.__init__ ran fmpz_is_probabprime on the modulus every time a context was created. Only a few operations use the result (discrete_log, and the fmpz_mod_poly / fmpz_mod_mpoly / fq_default paths that need a field), so for large moduli most of the cost of creating a context was a primality test nobody asked for.

As suggested in the issue, the test now runs the first time is_prime() is called and the result is cached. _is_prime changes from bint to int, with -1 meaning "not tested yet". Every internal user already goes through is_prime(), so nothing else changes. Under free-threading two threads may both run the test on the same context; they write the same value, so the race is harmless.

Context creation, Mersenne prime moduli (WSL, FLINT 3.6.0):

modulus before after (creation) first is_prime() after
2**4423 - 1 44 ms 0.19 ms 46 ms
2**11213 - 1 456 ms 0.06 ms 471 ms
2**19937 - 1 1.90 s 0.12 ms 1.87 s

Test: test_fmpz_mod_ctx_lazy_is_prime checks that creating the context costs less than a tenth of the first is_prime() call. It compares the two timings in the same run rather than using a fixed time limit. Before the change the first is_prime() is a cached lookup, so the test fails (≈41 ms vs ≈6 µs). The test also checks that the cached answer is correct for prime, composite and tiny moduli.

Checks run: pytest --doctest-modules src/flint (1097 passed), python -m flint.test (all 3152 doctests passed), cython-lint src/ (clean), Python 3.12, FLINT 3.6.0.

AI use: Claude Code (Claude Opus 5.5) wrote this change and the description, working on behalf of @KainanP. It ran all the tests listed above locally.

🤖 Generated with Claude Code

Creating an fmpz_mod_ctx ran a probable prime test on the modulus even
though only a few operations (discrete log, polynomial and mpoly
algorithms that require a field) use the result. For large moduli this
dominated the cost of creating the context. The test is now run the
first time is_prime() is called and the result is cached.

Fixes flintlib#333.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fmpz_mod_ctx always checks primality even if not needed

1 participant