FLINT3.7.0-dev
Algorithm

Divisibility testing by multiplication

Cost
One low product and one comparison per test; two words of precomputed data per divisor.

Testing d∣nd \mid n by computing n mod dn \bmod d is wasteful when only a yes or no answer is needed. Granlund and Montgomery [GraMon1994, §9] observed that for odd dd the test reduces to a multiplication modulo B=2FLINT_BITSB = 2^{\mathtt{FLINT\_BITS}}. FLINT uses it for trial division in n_is_prime and n_factor, and exposes it as n_divisible_odd_gm.

Theorem 1. Let dd be odd, d′=d−1 mod Bd' = d^{-1} \bmod B and L=⌊(B−1)/d⌋L = \lfloor (B - 1)/d \rfloor. For 0≤n<B0 \le n < B,

d∣n  ⟺  (nd′ mod B)≤L.d \mid n \iff (n d' \bmod B) \le L.

Moreover, if d∣nd \mid n then n/d=nd′ mod Bn/d = n d' \bmod B.

Proof. Since d′d' is odd, ϕ(n)=nd′ mod B\phi(n) = n d' \bmod B is a bijection of {0,1,…,B−1}\{0, 1, \ldots, B - 1\}. The multiples of dd in this range are kdkd for k=0,1,…,Lk = 0, 1, \ldots, L, and ϕ(kd)=kdd′ mod B=k\phi(kd) = k d d' \bmod B = k. So ϕ\phi maps the L+1L + 1 multiples of dd onto {0,…,L}\{0, \ldots, L\}. Being a bijection, it maps no other nn into this set. The second claim is ϕ(kd)=k\phi(kd) = k.

For even d=2ed0d = 2^e d_0, test that the lowest ee bits of nn are zero and that d0∣nd_0 \mid n.

Use in FLINT#

n_is_prime stores the pairs (d′,L)(d', L) for the 34 odd primes from 3 to 149 in a table. For n<232n < 2^{32} the 32 tests after 3 and 5 are written as a branch-free loop, which compilers vectorise. Trial division in n_factor uses the same test, and when it succeeds divides out the prime with the exact quotient nd′ mod Bn d' \bmod B from the theorem.

int n_divisible_odd_gm(ulong n, ulong inv1, ulong inv2)
void n_factor(n_factor_t * factors, ulong n, int proved)

Referenced from#

References#

Cite this page

The FLINT team, “Divisibility testing by multiplication,” FLINT: Fast Library for Number Theory, documentation, version 3.7.0-dev, 2026. https://flintlib.org/doc/algorithms/arithmetic/divisibility-test.html (generated 2026-11-02).