FLINT3.7.0-dev
Module · 108 functions

nmod.h

#include <flint/nmod.h>

This module implements arithmetic in Z/nZ\mathbb{Z}/n\mathbb{Z} for a word-size modulus n≥1n \ge 1. Elements are plain ulong values in [0,n)[0, n), and the modulus is passed as an nmod_t holding nn together with a precomputed inverse. Most functions are inline wrappers around the _preinv functions of ulong_extras. They are the scalar building blocks of nmod_vec, nmod_poly, nmod_mat and the other modules over Z/nZ\mathbb{Z}/n\mathbb{Z}. The module also provides square roots modulo primes, discrete logarithms, Montgomery arithmetic, and the generic ring (gr) contexts for Z/nZ\mathbb{Z}/n\mathbb{Z}.

The guides below explain how to use the module; start with Basic arithmetic modulo n. The conventions common to all FLINT modules, including the naming of functions and the use of nmod_t as a context, are described in Types, naming and aliasing.

Guides#

Conventions#

Throughout, B=2FLINT_BITSB = 2^{\mathtt{FLINT\_BITS}}.

A modulus nn with precomputed data, set up by nmod_init. The fields are n (the modulus), norm (the number of leading zero bits of nn) and ninv (the value n_preinvert_limb(n) used for Möller–Granlund division). An nmod_t is a small struct and is passed by value.

  • Reduced means 0≤a<n0 \le a < n. Unless stated otherwise, operands must be reduced and results are reduced. Functions named nmod_set_* and nmod_ui_* accept any input.
  • None of these assumptions is checked, except by FLINT_ASSERT in builds configured with --enable-assert.
  • A leading underscore marks a function with an extra restriction on the modulus or the input (for example _nmod_add), or an internal helper.
OverviewChoosing a method for modular arithmeticFLINT has a dozen ways to compute modulo a word-size nn, for single values, vectors, SIMD lanes and matrices. This page compares their requirements and costs and says which to use.

Initialisation and conversion#

void nmod_init(nmod_t * mod, ulong n)

Sets mod to the modulus nn, computing norm and ninv. Requires n≠0n \ne 0.

The number of bits of mod.n, that is, FLINT_BITS - mod.norm.

Return x mod nx \bmod n in [0,n)[0, n), for any xx.

Arithmetic#

Addition, multiplication, inversion and division of residues. The guide Basic arithmetic modulo n explains which of them need reduced operands and what to do when the divisor is not invertible.

Return a+ba + b, a−ba - b and −a-a modulo nn, for reduced operands and any nn.

Branch-free versions of nmod_add and nmod_sub. Require n≤2FLINT_BITS−1n \le 2^{\mathtt{FLINT\_BITS} - 1}; for larger nn the result is wrong.

Returns (a+b) mod n(a + b) \bmod n for any aa and bb.

Returns ab mod nab \bmod n for reduced operands and any nn.

Returns ab mod nab \bmod n for reduced operands. Requires mod.norm =0= 0, that is, n≥2FLINT_BITS−1n \ge 2^{\mathtt{FLINT\_BITS} - 1}. It saves the normalisation shift of nmod_mul.

Returns ab mod nab \bmod n for any aa and bb.

Return s+abs + ab and ab+cdab + cd modulo nn, for reduced operands. nmod_addmul forms s+abs + ab as a two-word integer and reduces it once.

NMOD_ADDMUL(r, a, b, mod)

Sets r to (r+ab) mod n(r + ab) \bmod n, for reduced r, a and b. This is r = nmod_addmul(r, a, b, mod).

Returns a−1 mod na^{-1} \bmod n for reduced aa. Throws an exception if gcd⁡(a,n)≠1\gcd(a, n) \ne 1.

Returns ab−1 mod na b^{-1} \bmod n for reduced aa and bb. Throws an exception if gcd⁡(b,n)≠1\gcd(b, n) \ne 1.

int nmod_divides(ulong * a, ulong b, ulong c, nmod_t mod)

If ac≡b(modn)ac \equiv b \pmod n has a solution, sets *a to one solution and returns 1; otherwise returns 0. Unlike nmod_div, this works when cc is not invertible. Requires reduced bb and cc.

More

Powering#

Return aexp mod na^{\mathit{exp}} \bmod n for reduced aa, with a0=1a^0 = 1 (which is 0 when n=1n = 1). For a negative exponent, nmod_pow_fmpz returns (a−1)−exp(a^{-1})^{-\mathit{exp}} and throws FLINT_IMPINV if aa is not invertible modulo nn.

More

Returns aexp mod na^{\mathit{exp}} \bmod n for any aa.

Returns 2exp mod n2^{\mathit{exp}} \bmod n.

More

The algorithms behind nmod_pow_ui and nmod_2_pow_ui, with the same results. The first two require exp≥1\mathit{exp} \ge 1 (they do not terminate for exp=0\mathit{exp} = 0), and _nmod_pow_ui_redc requires odd nn. _nmod_2_pow_ui_binexp accepts any nn and any exponent.

Square roots#

int nmod_sqrt(ulong * res, ulong a, nmod_t mod)

For prime nn and reduced aa: if aa is a square modulo nn, sets *res to the square root in [0,n/2][0, n/2] and returns 1; otherwise sets *res to 0 and returns 0. Primality is not checked. For composite nn, a return value of 1 still gives a genuine square root, but 0 does not prove that none exists.

Full documentation

For odd nn and a<na < n, finds the least square root of aa modulo nn by exhaustive search in O(n)O(n) steps. Returns 1 and sets *res to the root, or returns 0 and sets *res to 0 if there is none. The answer is correct for composite nn too.

Full documentation

The bound 128 below which nmod_sqrt uses _nmod_sqrt_small for odd nn.

AlgorithmSquare roots modulo a primeHow nmod_sqrt finds a square root modulo a word-size prime nn. It uses one exponentiation when n≡3(mod4)n \equiv 3 \pmod 4 or n≡5(mod8)n \equiv 5 \pmod 8, and otherwise Tonelli–Shanks in two forms or Müller's variant of Cipolla–Lehmer, depending on the power of 2 dividing n−1n - 1. Every candidate root is checked by squaring.

Discrete logarithms#

These functions compute discrete logarithms modulo a prime pp to the base of the least primitive root, by the Pohlig–Hellman method with baby-step giant-step. They are efficient when p−1p - 1 has only small prime factors. The guide Computing discrete logarithms shows how to use them, including logarithms to other bases.

Precomputed data for discrete logarithms modulo one prime: the factorisation of p−1p - 1, the primitive root and lookup tables. The field mod is an nmod_t for pp.

Sets up L for the prime pp, which is not checked, freeing any earlier data. Returns an estimate of the number of multiplications modulo pp needed by one call to nmod_discrete_log_pohlig_hellman_run.

Returns the base gg of the logarithms, the least primitive root modulo pp.

Returns the x∈[0,p−1)x \in [0, p - 1) with gx≡y(modp)g^x \equiv y \pmod p. Requires 0<y<p0 < y < p.

More
AlgorithmDiscrete logarithms modulo a prime (Pohlig–Hellman)Computes xx with gx=yg^x = y modulo a prime pp by solving the problem in each subgroup of prime-power order of (Z/pZ)×(\mathbb{Z}/p\mathbb{Z})^\times, one base-qq digit at a time, and combining the results by the Chinese remainder theorem. Fast when p−1p - 1 has only small prime factors.

Montgomery arithmetic#

In Montgomery arithmetic modulo an odd nn, a residue xx is represented by xR mod nx R \bmod n, where R=BR = B for the standard functions and R=2FLINT_BITS/2R = 2^{\mathtt{FLINT\_BITS}/2} for the half functions. Multiplication then needs no division. Values are converted into this Montgomery form once and back at the end. The prefix of a function name tells which representation it uses:

PrefixRequiresRRResidues
nmod_redc_odd nn2FLINT_BITS2^{\mathtt{FLINT\_BITS}}[0,n)[0, n)
nmod_redc_fast_odd n<2FLINT_BITS−2n < 2^{\mathtt{FLINT\_BITS} - 2}2FLINT_BITS2^{\mathtt{FLINT\_BITS}}[0,2n)[0, 2n)
nmod_redc_half_odd n<2FLINT_BITS/2−1n < 2^{\mathtt{FLINT\_BITS}/2 - 1}2FLINT_BITS/22^{\mathtt{FLINT\_BITS}/2}[0,n)[0, n)
nmod_redc_half_fast_odd n<2FLINT_BITS/2−2n < 2^{\mathtt{FLINT\_BITS}/2 - 2}2FLINT_BITS/22^{\mathtt{FLINT\_BITS}/2}[0,2n)[0, 2n)

The fast functions take and return lazy residues in [0,2n)[0, 2n), which saves a conditional subtraction per multiplication. The guide Using Montgomery arithmetic explains when Montgomery form pays off and the rules for mixing standard, fast and half functions.

AlgorithmMontgomery multiplication (REDC)Represents xx modulo an odd nn by xR mod nxR \bmod n, so that a modular product needs two word multiplications and a subtraction instead of a division. Lazy variants keep residues in [0,2n)[0, 2n) and skip the final correction.

A context for Montgomery arithmetic. The field mod is an ordinary nmod_t for nn, used for conversions and for addition, and nred is −n−1 mod R-n^{-1} \bmod R. The context needs no clearing.

Initialise ctx for the standard and fast functions modulo nn, which must be odd.

Returns whether n<2FLINT_BITS−2n < 2^{\mathtt{FLINT\_BITS} - 2}, the condition for the fast functions.

Return the Montgomery form xR mod nx R \bmod n of xx. nmod_redc_set_nmod requires x<nx < n; nmod_redc_set_ui accepts any xx.

Returns xR−1 mod nx R^{-1} \bmod n in [0,n)[0, n), converting from Montgomery form. Any word xx is accepted, in particular a lazy residue.

Negation, addition, subtraction and multiplication in Montgomery form, for inputs and output in [0,n)[0, n). Negation, addition and subtraction are the same as for ordinary residues.

The same operations on lazy residues: inputs and output are in [0,2n)[0, 2n). Require n<2FLINT_BITS−2n < 2^{\mathtt{FLINT\_BITS} - 2}.

Returns a lazy residue in [0,2n)[0, 2n) congruent to 2x2x, for x∈[0,2n)x \in [0, 2n).

Reduces a lazy residue x∈[0,2n)x \in [0, 2n) to [0,n)[0, n).

Return aexpa^{\mathit{exp}} with aa and the result in Montgomery form, by binary exponentiation. Require exp≥1\mathit{exp} \ge 1. The fast version takes and returns lazy residues.

Return the Montgomery form of 2exp2^{\mathit{exp}}, for any exp\mathit{exp}. The fast version returns a lazy residue.

Half-word Montgomery arithmetic#

These functions use R=2FLINT_BITS/2R = 2^{\mathtt{FLINT\_BITS}/2}, so that every product fits in one word. They take the same context type, but it must be initialised with the functions below, and the resulting Montgomery form differs from that of the full-word functions, so the two cannot be mixed.

Initialise ctx for the half functions modulo nn, which must be odd with n<2FLINT_BITS/2−1n < 2^{\mathtt{FLINT\_BITS}/2 - 1}.

Returns whether n<2FLINT_BITS/2−2n < 2^{\mathtt{FLINT\_BITS}/2 - 2}, the condition for the half_fast functions.

Convert to and from Montgomery form with R=2FLINT_BITS/2R = 2^{\mathtt{FLINT\_BITS}/2}. nmod_redc_half_set_nmod requires x<nx < n and nmod_redc_half_set_ui accepts any xx. nmod_redc_half_get_nmod returns a value in [0,n)[0, n) for any x<nRx < nR, in particular for lazy residues.

Addition, subtraction and multiplication in Montgomery form, for inputs and output in [0,n)[0, n).

The same on lazy residues in [0,2n)[0, 2n). Require n<2FLINT_BITS/2−2n < 2^{\mathtt{FLINT\_BITS}/2 - 2}.

Low-level functions#

The context functions are wrappers of the following ones, which take the odd modulus nn and nred =−n−1 mod R= -n^{-1} \bmod R directly. Here R=BR = B, except for the half functions, where R=2FLINT_BITS/2R = 2^{\mathtt{FLINT\_BITS}/2}.

Return xR−1 mod nx R^{-1} \bmod n for any word xx. n_redc_fast returns a value in [0,n][0, n], which may need one more subtraction of nn.

Return a value congruent to xR−1x R^{-1} modulo nn, for a two-word xx. n_ll_redc requires x<nBx < nB and returns a value in [0,n)[0, n). n_ll_redc_fast requires x+(B−1)n<B2x + (B - 1) n < B^2 and returns a value below x/B+nx/B + n.

Return a value congruent to abR−1ab R^{-1} modulo nn. n_mulmod_redc requires ab<nBab < nB (for example a,b<na, b < n) and returns a value in [0,n)[0, n). n_mulmod_redc_fast maps a,b∈[0,2n)a, b \in [0, 2n) to [0,2n)[0, 2n) when n<2FLINT_BITS−2n < 2^{\mathtt{FLINT\_BITS} - 2}.

Returns aB mod na B \bmod n for a<na < n, given ninv and norm as stored in an nmod_t for nn. This is one division step with the precomputed inverse.

The same with R=2FLINT_BITS/2R = 2^{\mathtt{FLINT\_BITS}/2}. The reductions require x+(R−1)n<Bx + (R - 1) n < B, and the ranges of inputs and outputs are those of the corresponding nmod_redc_half functions. n_to_redc_half_preinv ignores norm.

An unsigned two-word integer: __uint128_t when compiling for a 64-bit machine with a GCC-compatible compiler, and otherwise a struct of two words lo and hi. It exists for the Montgomery helpers above and may change.

Construct the two-word integer hiB+lo\mathit{hi} B + \mathit{lo}, and return the high or the low word of xx.

Return (x+y) mod B2(x + y) \bmod B^2, and the full product xyxy of two words.

Generic rings#

These functions create gr contexts for Z/nZ\mathbb{Z}/n\mathbb{Z}. Those without redc in the name are declared in gr.h.

Initialise ctx for the ring Z/nZ\mathbb{Z}/n\mathbb{Z} in the given representation and return GR_SUCCESS. If n=0n = 0, return GR_DOMAIN; if nn violates the restrictions of the representation, return GR_UNABLE. In both cases ctx is not initialised.

More
void _gr_ctx_init_nmod(gr_ctx_t ctx, void * nmod_t_ref)

Initialises ctx like gr_ctx_init_nmod, copying the nmod_t that nmod_t_ref points to instead of recomputing it.

The nmod_t stored in a context created by gr_ctx_init_nmod, and a pointer to it.

A pointer to the nmod_redc_ctx_struct stored in a context created by gr_ctx_init_nmod_redc or gr_ctx_init_nmod_redc_fast.

Low-level macros#

These macros are the building blocks of the arithmetic functions above and of the vector, polynomial and matrix modules. Most reduce two or three words modulo nn with one or two steps of Möller–Granlund division; NMOD_RED reduces one word by Barrett reduction. Unless stated otherwise, the first argument receives the result and mod is an nmod_t. A pair a_hi, a_lo stands for the two-word integer ahiB+aloa_{hi} B + a_{lo}.

NMOD_RED(r, a, mod)

Sets r to a mod na \bmod n for any word aa and any nn. It uses one high and one low product (none if nn has FLINT_BITS bits), with a constant derived from mod.ninv (Barrett reduction with an nmod_t), and is cheaper than reducing aa as a two-word number with NMOD_RED2.

NMOD_RED2(r, a_hi, a_lo, mod)

Sets r to (ahiB+alo) mod n(a_{hi} B + a_{lo}) \bmod n. Requires ahi<na_{hi} < n.

NMOD2_RED2(r, a_hi, a_lo, mod)

Sets r to (ahiB+alo) mod n(a_{hi} B + a_{lo}) \bmod n with no restriction on ahia_{hi}. It reduces ahia_{hi} first with NMOD_RED, then applies NMOD_RED2.

NMOD_RED3(r, a_hi, a_me, a_lo, mod)

Sets r to (ahiB2+ameB+alo) mod n(a_{hi} B^2 + a_{me} B + a_{lo}) \bmod n. Requires ahi<na_{hi} < n.

NMOD_RED2_FULLWORD(r, a_hi, a_lo, mod)
NMOD_RED2_NONFULLWORD(r, a_hi, a_lo, mod)

Versions of NMOD_RED2 without the test on mod.norm. NMOD_RED2_FULLWORD requires mod.norm =0= 0 (the top bit of nn is set) and NMOD_RED2_NONFULLWORD requires mod.norm >0> 0. Both require ahi<na_{hi} < n.

NMOD_MUL_PRENORM(res, a, b, mod)
NMOD_MUL_FULLWORD(res, a, b, mod)

Multiply without the operand shift done by nmod_mul. NMOD_MUL_PRENORM requires a<na < n and b=c 2normb = c\, 2^{\mathit{norm}} with c<nc < n, that is, bb is a reduced value already shifted left by mod.norm bits, and sets res to the reduced residue ac mod nac \bmod n; nmod_mul(a, c, mod) is this macro applied to a and c << mod.norm. NMOD_MUL_FULLWORD requires mod.norm =0= 0 and reduced operands, and sets res to ab mod nab \bmod n.

Nonzero if n<2FLINT_BITS−1n < 2^{\mathtt{FLINT\_BITS} - 1}, the condition for multiplication by a fixed operand with n_mulmod_shoup.

Cite this page

The FLINT team, “nmod.h (module overview),” FLINT: Fast Library for Number Theory, documentation, version 3.7.0-dev, 2026. https://flintlib.org/doc/nmod/index.html (generated 2026-11-02).