Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/flint/test/test_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -1913,6 +1913,31 @@ def test_pickling():
assert obj == obj2


def test_fmpz_mod_ctx_lazy_is_prime():
from flint import fmpz_mod_ctx, fmpz_mod
import time

# Creating a context should not test the modulus for primality: the
# result is only needed by operations such as division (gh-333).
p = 2**4423 - 1 # Mersenne prime: the probable prime test takes a while
t0 = time.perf_counter()
F = fmpz_mod_ctx(p)
t1 = time.perf_counter()
assert F.is_prime() is True
t2 = time.perf_counter()
assert (t1 - t0) * 10 < t2 - t1

# The cached result is used for the checks that need it.
assert F.is_prime() is True
assert F(3) / F(2) == F(3) * F(2).inverse()

F_cmp = fmpz_mod_ctx(2**4423 + 1)
assert F_cmp.is_prime() is False
assert fmpz_mod_ctx(1).is_prime() is False
assert fmpz_mod_ctx(2).is_prime() is True
assert fmpz_mod_ctx(4).is_prime() is False


def test_fmpz_mod():
from flint import fmpz_mod_ctx, fmpz, fmpz_mod

Expand Down
2 changes: 1 addition & 1 deletion src/flint/types/fmpz_mod.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ from flint.flintlib.functions.fmpz_mod cimport (

cdef class fmpz_mod_ctx:
cdef fmpz_mod_ctx_t val
cdef bint _is_prime
cdef int _is_prime # -1 until the modulus has been tested
cdef bint _init_L
cdef fmpz_mod_discrete_log_pohlig_hellman_t L

Expand Down
9 changes: 6 additions & 3 deletions src/flint/types/fmpz_mod.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ cdef class fmpz_mod_ctx:
# Set the modulus
fmpz_mod_ctx_set_modulus(self.val, (<fmpz>mod).val)

# Check whether the modulus is prime
# TODO: should we use a stronger test?
self._is_prime = fmpz_is_probabprime(self.val.n)
# Testing the modulus for primality can be expensive, so it is only
# done the first time is_prime() is called.
self._is_prime = -1

def modulus(self):
"""
Expand All @@ -95,6 +95,9 @@ cdef class fmpz_mod_ctx:
>>> fmpz_mod_ctx(2**127 - 1).is_prime()
True
"""
if self._is_prime == -1:
# TODO: should we use a stronger test?
self._is_prime = fmpz_is_probabprime(self.val.n)
return self._is_prime == 1

def zero(self):
Expand Down