Reference

Everything in the library

Every export of @ratmath/numtheory. Whole-number arguments may be numbers, BigInts, digit strings or Core Rationals with denominator 1; a JavaScript number that is not whole is refused. Results are BigInts, except symbols (−1, 0, 1) and valuations, which are plain numbers. Refusals throw a NumberTheoryError whose code says why.

Primes and certificates

ExportWhat it does
primes(limit)The primes up to the limit (at most 10⁷), by the sieve of Eratosthenes.
primePi(x), nthPrime(k)π(x)\pi(x) exactly, up to 10¹² (a sieve below 10⁷, Meissel's formula above); the k-th prime.
isPrime(n)Proven below 2⁶⁴ (Baillie–PSW); above, by a certificate, or throws "unproven".
isProbablePrime(n)Baillie–PSW alone: fast, not a proof above 2⁶⁴.
nextPrime(n), prevPrime(n), primesBetween(a, b)Neighbouring primes; the primes in a window (segmented sieve, b < 2⁶⁴).
provePrime(n, { budget, elliptic, maxDiscriminant, maxClassNumber }){ prime, proven, certificate | factor | witness | reason }: a Pocklington, Brillhart–Lehmer–Selfridge or elliptic curve certificate, a factor or a Miller–Rabin witness, or the reason none was found. elliptic: false uses n − 1 only.
classPolynomial(D)The Hilbert class polynomial HDH_D of a negative discriminant, coefficients constant term first; its degree is the class number.
verifyCertificate(cert)The independent checker: { valid: true } or { valid: false, reason }. Shares no code with the search.
verifyComposite(n, { factor, witness })Checks a proof of compositeness.
millerRabinWitness(n, a)True when a proves n composite by the strong test.
PROVEN_BELOW2⁶⁴.

Factoring

ExportWhat it does
factor(n, { prove, effort })[{ prime, exponent, proven }], increasing: trial division, Pollard rho, p − 1, then the elliptic curve method. Refuses with "too-hard" when the factors are out of reach; effort scales the number of curves.
ecm(n, { B1, B2, curves, sigma, details })The elliptic curve method: a proper factor or null; with details, { factor, stage, sigma, B1, B2 }.
ecmCurve(n, sigma, { B1, B2 })One Suyama curve, as a report.
formatFactors(fs)"2^3 · 3 · 5^2".
trialDivide(n, limit){ found: Map(prime → exponent), rest }.
pollardRho(n, { steps, seed })A nontrivial factor by Brent's rho, or null.
pollardPm1(n, bound)A factor p with p − 1 smooth to the bound, or null.
factorInteger, modPow, modInverse, multiplicativeOrder, primitiveRoot, discreteLogMod, sqrtMod, lll, recognizeRe-exported from @ratmath/algebraic, which keeps the modular kernel for its finite fields.

Arithmetic functions

ExportWhat it does
divisors(n)The positive divisors, increasing.
sigma(n, k), tau(n)σk(n)=∑d∣ndk\sigma_k(n) = \sum_{d \mid n} d^k (k = 1 by default); the number of divisors.
totient(n), jordan(n, k), carmichael(n)Euler's φ\varphi, Jordan's JkJ_k, Carmichael's λ\lambda.
mobius(n), liouville(n)μ(n)\mu(n) and λ(n)=(−1)Ω(n)\lambda(n) = (-1)^{\Omega(n)}.
omega(n), bigOmega(n), radical(n), isSquarefree(n)Distinct primes, primes with multiplicity, their product, square-freeness.
aliquotSum(n), classify(n), isPerfect(n)s(n)=σ(n)−ns(n) = \sigma(n) - n; "perfect", "abundant" or "deficient".
aliquotSequence(n, { steps, max }){ terms, ending }: "terminates", "perfect", "amicable", "cycle of length k" or "unfinished".
amicablePairs(limit), perfectNumbers(count), lucasLehmer(p)Amicable pairs up to the limit; even perfect numbers; the Lucas–Lehmer test of 2ᵖ − 1.
dirichlet(f, g), mobiusInversion(F)Dirichlet convolution; f=F∗μf = F * \mu.
unit, one, idε\varepsilon, the constant 1, the identity: building blocks for convolutions.
isMultiplicative(f, limit)Checks f(mn)=f(m)f(n)f(mn) = f(m)f(n) on coprime pairs up to the limit (a check, not a proof).

Congruences

ExportWhat it does
solveLinear(a, b, m)Every x mod m with ax≡bax \equiv b: { solutions, modulus, g, reduced }, or no solutions with the reason.
crt(residues, moduli)The Chinese remainder theorem for any moduli: { x, modulus } or null.
solveLinearSystem([[a, b, m], …])Each aix≡bi(modmi)a_ix \equiv b_i \pmod{m_i} reduced, then combined.
polyMod(poly, x, m)An integer polynomial (constant first) at x, mod m.
hensel(poly, r, p, k)Lifts a simple root mod p to the root mod pkp^k.
rootsMod(poly, m)Every root mod m: prime powers by lifting, combined by CRT.
hasPrimitiveRoot(n), primitiveRootMod(n), order(a, n)Gauss's condition; the least primitive root or null; the multiplicative order.
discreteLog(g, h, n)The least x with gx≡hg^x \equiv h, or null (baby-step giant-step).
valuation(n, p)vp(n)v_p(n); Infinity for 0.
factorialValuation(n, b)The exponent of bb in n!n!: Legendre's formula ∑k⌊n/pk⌋\sum_k \lfloor n/p^k\rfloor for a prime; the largest kk with bk∣n!b^k \mid n! for any b≥2b \ge 2 (trailing zeros in base bb). A BigInt when too large for a plain number.

Reciprocity

ExportWhat it does
legendre(a, p), jacobi(a, n), kronecker(a, n)The quadratic symbols, as −1, 0 or 1.
jacobiSteps(a, n){ value, steps }: the reciprocity computation, one line per step.
eulerCriterion(a, p), gaussLemma(a, p){ power, value }; { value, mu, large }.
quadraticResidues(n), sqrtsMod(a, n)The squares mod n; every square root of a mod n.

Sums of squares

ExportWhat it does
primeAsTwoSquares(p)p ≡ 1 (mod 4) as a2+b2a^2 + b^2, by Euclid's algorithm on p and a square root of −1 (Brillhart).
twoSquaresAll(n), twoSquares(n), twoSquaresReason(n)Every a2+b2=na^2 + b^2 = n with a≥b≥0a \ge b \ge 0 (Gaussian integers); one; why or why not.
r2(n), r4(n), rk(n, k)Representations counted with signs and order: Jacobi's formulas, and the theta series for any k ≤ 12.
threeSquares(n), fourSquares(n)Three squares unless n=4a(8b+7)n = 4^a(8b + 7) (then null); four always.
pythagoreanTriples(limit)Primitive triples with c ≤ limit, by Euclid's formula.
triplesWithHypotenuse(c), triplesWithLeg(a)Every triple, primitive or not, with that hypotenuse or leg.

Diophantine equations

ExportWhat it does
linearDiophantine(coefficients, c){ solvable, g, particular, basis }: every solution is the particular one plus an integer combination of the basis.
nonNegativeSolutions(a, b, c)The solutions of ax + by = c in non-negative integers.
frobenius(coins), coinWays(amount, coins)The largest unpayable amount; the number of ways to pay.
pellSolutions(D, N), normEquation(D, N)x2−Dy2=Nx^2 - Dy^2 = N: { kind: "infinite", unit, fundamental, solutions(count) } or { kind: "finite", solutions }.
egyptianGreedy(q), egyptianShortest(q, options)Distinct unit fractions: greedy, or a shortest expansion by search.

Continued fractions

ExportWhat it does
continuedFraction(x, terms)The terms of a rational or real algebraic number, exactly.
convergents(terms)The convergents as Core Rationals.
fromContinuedFraction(terms, period)The number [a₀; a₁, …] or [preperiod; period repeating], as an AlgebraicReal.
periodicContinuedFraction(x){ preperiod, period } of a quadratic irrational.
pell(D), fundamentalUnit(d), fromQuadratic(p, q, d, r)The least solution of x2−Dy2=±1x^2 - Dy^2 = \pm 1; the fundamental unit of Q(d)\mathbb Q(\sqrt d); (p+qd)/r(p + q\sqrt d)/r as an AlgebraicReal.

Binary quadratic forms

ExportWhat it does
form(a, b, c), new Form(a, b, c)ax2+bxy+cy2ax^2 + bxy + cy^2: discriminant, at(x, y), transform(M), reduce() → { form, matrix }, cycle(), isReduced(), isPrimitive().
equivalent(f, g){ equivalent: true, matrix } with f ∘ matrix = g, or false with the reason.
compose(f, g), principalForm(D), inverseForm(f)Gauss composition (reduced); the identity class; the inverse class.
reducedForms(D), classNumber(D)One reduced form per class; h(D), the narrow one for D > 0.
classGroup(D){ D, h, forms, identity, classOf, compose, inverse, order, structure }; structure lists the invariant factors.
representations(f, n), represent(f, n)Every (x, y) with f(x, y) = n for definite f; one proper representation for any D, or null.

Elliptic curves

ExportWhat it does
ellipticCurve([a, b]), ellipticCurve([a1, a2, a3, a4, a6])A curve over Q\mathbb{Q}; with { mod: p }, over Fp\mathbb{F}_p. An EllipticCurve, with a1 … a6, b2 … b8, c4, c6, discriminant, j, modulus, coefficients, infinity.
E.point(x, y), E.has(P), E.equal(P, Q)A checked point { x, y }; membership; equality.
E.add(P, Q), E.sub(P, Q), E.neg(P), E.double(P), E.mul(k, P)The group law.
E.order(P)A BigInt; over Q\mathbb{Q}, Infinity for a point of infinite order.
E.torsion()Over Q\mathbb{Q}: { order, structure, points, generators }.
E.shortModel(), E.minimalModel(){ curve, to(P), from(P), … }: a short integral model; the global minimal model with its change of variables u, r, s, t.
E.badPrimes(), E.reduction(p), E.conductor(), E.modulo(p)Reduction: { prime, type, split, discriminantValuation, conductorExponent }; the conductor when no additive prime is 2 or 3; the curve over Fp\mathbb{F}_p.
E.naiveHeight(P), E.height(P, { doublings })H(P)H(P); a proven enclosure { lower, upper, exact } of the canonical height.
E.rationalPoints(bound)A search for points of small height.
E.count({ method, log }), E.trace()Over Fp\mathbb{F}_p: the number of points by "naive", "bsgs", "schoof" or "auto"; the trace of Frobenius.
E.points(), E.liftX(x), E.randomPoint(seed), E.structure()All points (p ≤ 10⁶); the points above an x; a reproducible point; the group as Z/n1×Z/n2\mathbb{Z}/n_1 \times \mathbb{Z}/n_2.
E.divisionPolynomial(n)Coefficients of the n-th division polynomial of a short curve over Fp\mathbb{F}_p.

p-adic numbers

ExportWhat it does
padic(x, p)A p-adic number from a whole number, fraction text, Rational or another p-adic.
Padicapprox(N), valuation(), norm(), digits(k), toString(k), mod(N), add, sub, mul, div, inv, pow, shift, sqrt, isSquare, exp, log, equalsTo(y, N). Lazy and exact; an undecidable valuation throws "unknown-valuation".
henselRoot(coefficients, r0, p)The root of a polynomial starting at r0, by Newton's method.
teichmuller(a, p)The (p − 1)-th root of unity ≡ a (mod p).
expansion(x, p){ valuation, preperiod, period } of a rational's eventually periodic digits.
padicValuation(x, p), padicNorm(x, p)vp(x)v_p(x) and ∣x∣p|x|_p of a rational.

Number fields

ExportWhat it does
NumberField, NumberFieldElementRe-exported from @ratmath/algebraic. Wherever a field is expected, the coefficients of an irreducible polynomial (constant first) work too.
ringOfIntegers(K)The ring of integers, an Order, by the Round 2 algorithm; cached on the field.
Orderbasis, discriminant, index, polyDiscriminant, signature, steps, traceMatrix, ramifiedPrimes, coordinates(x), element(coords), contains(x), primesAbove(p), describePrime(p), ideal(...generators), unitIdeal.
integralBasis(K), fieldDiscriminant(K), primeDecomposition(K, p)Shortcuts for the basis, the discriminant and primesAbove.
PrimeIdealp, e, f, norm, generators, valuation(x) of an element, ideal or prime, toIdeal(), equals.
IdealA fractional ideal: norm, basis, minimum, isIntegral, isOne, isPrime, mul, add, div, pow, inverse, contains(x), equals, factor() as [{ prime, exponent }].
idealClassGroup(K, options)A ClassGroup: h, structure, generators, classOf(I), orderOf(I), isPrincipal(I) as { principal, generator }, proven, certificate, minkowskiBound, factorBase. Options certify, maxBound, maxIndexPrime, budget, rounds.
unitGroup(K, options)A UnitGroup: rank, torsionOrder, rootOfUnity, fundamentalUnits, regulator, isUnit(x), exponents(u) as { torsion, exponents }, proven, certificate.
fieldClassNumber(K), regulator(K), minkowskiBound(K)The class number, the regulator (a double), and the floor of Minkowski's bound.
formToIdeal(f, K)The ideal aZ+−b+D2Za\mathbb{Z} + \tfrac{-b + \sqrt D}{2}\mathbb{Z} of the quadratic field of discriminant D for a form (a, b, c).

Counting primes, characters, zeta and L values

ExportWhat it does
meissel(x){ pi, y, a, phi, P2 }: π(x)=φ(x,a)+a−1−P2\pi(x) = \varphi(x, a) + a - 1 - P_2 with a=π(x3)a = \pi(\sqrt[3]{x}), for x ≤ 10¹².
legendrePhi(x, a)How many n ≤ x have no prime factor among the first a primes.
dirichletCharacter(q, m)The character χq(m,⋅)\chi_q(m, \cdot) in Conrey's numbering, a DirichletCharacter.
DirichletCharactermodulus, number, order, conductor, isPrimitive, isPrincipal, isReal, isEven, parity, exponent(n) (the fraction t with χ(n)=e2πit\chi(n) = e^{2\pi i t}, or null), value(n), at(n) for real characters, exponents(), primitive(), induce(modulus), mul, pow, conjugate, gaussSum().
dirichletGroup(q){ modulus, order, characters, principal, primitive, real, structure, orthogonality(a, b) }, for q ≤ 20000.
kroneckerCharacter(D)The Kronecker symbol (D/⋅)(D/\cdot) as a character modulo |D|.
bernoulli(n), bernoulliPolynomial(n, x), generalizedBernoulli(k, χ)BnB_n (with B1=−1/2B_1 = -1/2), Bn(x)B_n(x), and Bk,χB_{k,\chi}.
zetaExact(n)A Rational for n ≤ 0; { coefficient, piPower } for even n > 0.
lValueExact(χ, n)L(n,χ)L(n, \chi) for an integer n ≤ 0: a Rational for a real character, else an element of a cyclotomic field.
zetaValue(s, { bits })A proven enclosure of ζ(s)\zeta(s): a RationalInterval for real s, { re, im } for [σ, t]. Width below 2−bits2^{-\text{bits}}, 64 by default.
hurwitzZeta(s, a, { bits })An enclosure of ζ(s,a)\zeta(s, a) for a rational a in (0, 1].
lValue(χ, s, { bits })An enclosure of L(s,χ)L(s, \chi) anywhere in the plane (modulus ≤ 5000); at s = 1 for a non-principal character.

Integers and the rest

ExportWhat it does
isqrt(n), iroot(n, k), gcd(a, b), lcm(a, b), egcd(a, b)Integer roots, gcd and lcm, and Bézout's { g, x, y }. Any whole number in (number, BigInt, numeric string, Core Integer or whole Rational); BigInts out.
NumberTheoryErrorThrown for refusals; code is one of "bad-argument", "too-large", "too-hard", "unproven", "unknown-valuation", "not-a-square", "diverges", "singular", "not-on-curve", "budget", "pole", "precision", "unsupported".
planThe phases still to come: empty, everything planned is built.
Try itEdit the code and run it with @ratmath/numtheory and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs