Fast, integer-backed algebraic number types for exact arithmetic in quadratic integer rings (imaginary and real), plus the dual and split-complex integers.
-
complexint: a Gaussian integer type that mirrors Python’scomplex, but storesintcomponents (no floating-point drift). -
QuadInt/QuadraticRing: a general quadratic-integer implementation for elements of the form
$(a + b\sqrt{D}) / \mathrm{den}$ with$den ∈ {1,2}$ .- By default,
QuadraticRing(D)choosesden = 2whenD % 4 == 1, otherwiseden = 1(and you can override withQuadraticRing(D, den=1)to work in the non-maximal order$\mathbb{Z}[\sqrt{D}]$ ).den=2is only allowed whenD % 4 == 1, since otherwise these numbers are not closed under multiplication.
- By default,
-
eisensteinint: Eisenstein integers in the ω-basis (a + bω, where$ω = (-1 + \sqrt{-3})/2$ ). -
dualint: dual integers of the forma + bεwhereε² = 0andε != 0. -
splitint: split-complex (hyperbolic) integers of the forma + bjwherej² = 1andj != 1.
Designed for discrete math, number theory tooling, and high-throughput exact computations (this project is built to compile cleanly with mypyc).
Helper methods on every quadratic integer value:
x.content()— largest positive integernsuch thatx = n*yin the same ring.x.gcd(y),x.xgcd(y),x.inv_mod(m), andpow(x, e, m)— gcds and modular arithmetic, in the principal ideal domains (see below).x.factor_detail()— structured factorization asFactorization(unit, primes).x.factor()— a plain{prime_like_factor: exponent}mapping whose product is exactlyx.x.basis,x.basis_a,x.basis_b— public/user-facing basis coordinates, which may differ from the internal(a, b)numerator coordinates.
python -m pip install quadintfrom quadint import complexint
a = complexint(1, 2)
b = complexint(3, 6)
c = a * b
print(c) # "(-9+12j)" (exact, integer-backed)
print(c.real) # -9
print(c.imag) # 12
print(type(c.real)) # <class 'int'>
print(abs(a)) # 1^2 + 2^2 = 5 (norm)complexint is ideal when you want something that feels like complex, but with infinite-precision integer components.
Create a ring instance for a chosen discriminant parameter D, then construct values in that ring:
from quadint import QuadraticRing
Q2 = QuadraticRing(-2) # Z[√-2]
x = Q2(1, 2) # (1 + 2*sqrt(-2))
y = Q2(3, 6)
print(x * y) # "(-21+12*sqrt(-2))"
print(abs(x)) # norm: 1^2 - (-2)*2^2 = 9Common operations include +, -, *, ** (non-negative powers, negative ones of units, whose inverse ~x is in the ring, or negative ones of anything with a modulus, as in pow(x, -1, m)), conjugate(), abs() (the norm), and .trace (x + x.conjugate()).
The two arguments are the numerators of den == 2 (the default when D % 4 == 1), where a and b must have the same parity:
from quadint import QuadraticRing
Z5 = QuadraticRing(5) # den=2, so this is Z[(1 + √5)/2]
phi = Z5(1, 1) # (1 + √5)/2, the golden ratio
print(phi * phi) # (3+1*sqrt(5))/2
print(phi * phi == phi + 1) # True
print(Z5(2, 0) == 1) # True: 1 is 2/2 here, and Z5(1, 0) raises ValueError
print(Z5.from_ab(1, 1)) # (2+2*sqrt(5))/2, since from_ab takes a + b√D directly
print(Z5.fundamental_unit()) # (1+1*sqrt(5))/2from quadint.eisenstein import eisensteinint
z = eisensteinint(2, 3) # 2 + 3ω
w = eisensteinint(1, -1) # 1 - ω
print(z) # (2+3ω)
print(z * w) # (5+4ω), the exact product in Z[ω]
print(abs(z)) # 7, the norm a^2 - ab + b^2Use real and omega to access the ω-basis components.
from quadint import dualint
z = dualint(2, 3) # 2 + 3ε
w = dualint(1, -1) # 1 - ε
print(z) # (2+3ε)
print(z * w) # (2+1ε)Use real and dual (or epsilon) to access the ε-basis components.
ε is a zero divisor (ε * ε == 0), so its multiples have no real part, and there is no remainder to make small: divmod by a multiple of ε raises ZeroDivisionError. Exact division still works, though:
from quadint import dualint
print(dualint(0, 6).exact_div(dualint(0, 2))) # (3+0ε) (any 3 + kε would do, since 2ε * kε == 0)
print(dualint(0, 1).divides(dualint(5, 7))) # False (5 + 7ε has a real part)Split-complex (a.k.a. hyperbolic) integers behave like complexint, except the generator satisfies j² = 1 instead of j² = -1.
Unlike complex numbers, split-complex numbers have an indefinite norm and zero divisors (e.g. (1+j)*(1-j) == 0).
from quadint.split import splitint
z = splitint(1, 1) # 1 + 1j
w = splitint(1, -1) # 1 - 1j
print(z * w) # 0j (zero divisor behavior)-
This package is primarily intended for exact, discrete arithmetic (
+,-,*,**, conjugation, norms). -
Division (
divmod,//,%, and/, which gives the same rounded quotient as//) is implemented for the Euclidean maximal orders (the defaultden), and for the dual (D=0) and split-complex (D=1) integers.ring.supports_division()says whether a ring has it, and rings without it raiseNotImplementedError. The Euclidean rings are:- the norm-Euclidean ones:
D=-1,-2,-3,-7,-11andD=2,3,5,6,7,11,13,17,19,21,29,33,37,41,57,73, D=69, via Clark's Euclidean function,- and real quadratic rings that are Euclidean but not norm-Euclidean, via a Harper-style method (a weighted Euclidean score plus a quotient search). Witnesses are built in for
D=14,22,23,31,43,46,47,53,59,61,62,67,71,77,83,86,89,93,94,97, and any other realDwhose maximal order has class number one is checked when the ring is created (D=38,101,103, and so on): it qualifies if its discriminant is at most 500, or if an admissible pair of witness primes turns up below 200.
- the norm-Euclidean ones:
-
In the Harper-style rings,
divmod,//and%can raiseNotImplementedErrorfor some inputs, because the weighted score is not a Euclidean function for every pair (every remainder of1 + √14modulo2has a larger weighted norm than2, for example).gcd,xgcd,inv_modandpow(x, e, m)don't use that search, so they aren't affected. -
The quotient is found near
x / yrounded, with halves rounding up (toward +∞), and anything else that picks among quotients is relative to that. So the remainder only depends onxmoduloy:x % y == (x + h * y) % yfor anyhin the ring, reducing again changes nothing, andpow(x, e, m) == (x ** e) % m, as for anint, wherever%works. -
gcd,xgcdandinv_modare available in every principal ideal domain, which is the maximal orders with class number one. That includes every Euclidean ring above, and alsoD=-19,-43,-67,-163, which have no division, so their gcds come from generators of ideals instead.pow(x, e, m)works in all of those, and anywhere else with division. Other rings raiseNotImplementedError, except for the split-complex integers, which have gcds of their own: theden=2ones have all of these, and theden=1ones havegcd(but notxgcdorinv_mod). A gcd is only defined up to a unit, so it is normalized to a positive leading coefficient (the first quadrant in the Gaussian integers, the first sextant in the Eisenstein integers), and coprime elements have gcd1. -
Factorization (
factor/factor_detail) is implemented for the same principal ideal domains, imaginary and real:complexint(D=-1),QuadraticRing(-2), andeisensteinint(D=-3),- the maximal orders for
D=-7,-11,-19,-43,-67,-163, - and the real ones: every real Euclidean ring above, and any other real maximal order with class number one. A prime there has infinitely many associates (times any power of the fundamental unit), so each prime comes out as its most compact one, and the unit takes the rest:
QuadraticRing(2)(7).factor_detail()has the unit-1and the primes1 + 2√2and1 - 2√2.
Every prime comes out normalized the way a gcd is (a positive leading coefficient, the first quadrant in the Gaussian integers, the first sextant in the Eisenstein integers), so
complexint(5).factor_detail()has the unit-1jand the primes1 + 2jand2 + 1j. Other rings raiseNotImplementedError. -
Floats and Python
complexare accepted in some operations but are converted viaint(...), which truncates toward zero. If you care about rationals, avoid mixing infloat.- Equality is the exception, and is exact:
complexint(1) == 1.9isFalse. A value that equals a Python number also hashes like it, socomplexint(1)and1are the same dict key (as1and1.0are), and likewisecomplexint(1, 2)and1+2j.
- Equality is the exception, and is exact:
Example of truncation behavior:
from quadint import complexint
a = complexint(3, 6)
print(a / 3) # "(1+2j)"
print(a / 3.5) # "(1+2j)" (3.5 -> 3 by int(...) conversion)
print(a + 1) # "(4+6j)"
print(a + 1.5) # "(4+6j)" (1.5 -> 1)quadint can work with integral ideals of quadratic orders.
from quadint import QuadraticRing
O = QuadraticRing(-5) # Z[√-5]
I = O.ideal(3, O(1, 1)) # (3, 1 + √-5)
print(I.is_prime, I.is_principal) # True False
print((I**2).principal_generator()) # (2-1*sqrt(-5)), so I**2 is the principal ideal (2 - √-5)
print([P.norm for P in O.ideal(6).factor()]) # [2, 2, 3, 3]: (6) factors into four prime ideals
print(O.class_number) # 2
J = O.ideal(2) + O.ideal(O(1, 1)) # the ideal that 2 and 1 + √-5 generate together
print(J.norm, J.is_principal) # 2 FalseI + J is the smallest ideal holding both, which in a maximal order is their gcd. So two elements with no gcd in the ring, like 2 and 1 + √-5 here, still have one as ideals. A number stands for its principal ideal (I + x, like I * x), so sum() works on ideals too.
Principal generators come from lattice reduction in imaginary rings and continued fractions in real ones, so this stays fast for large ideals. Class groups (O.class_group, O.class_number) are available for maximal orders, real and imaginary. Each class (IdealClass(I)) is pinned down by a reduced form, the reduced binary quadratic form in imaginary rings and the smallest reduced ideal in the class in real ones, so classes compare and hash quickly, and products and powers of classes keep small representatives. Non-maximal orders such as QuadraticRing(-3, den=1) raise NotImplementedError.
QuadInt separates public basis coordinates from the internal numerator coordinates used by the arithmetic engine.
Internally, every value is still stored as (a, b) numerators for
For most quadratic integer types, the public basis is the identity basis, so the coordinates you pass to the constructor are the same coordinates used internally. Subclasses can override that by defining conversion matrices:
BASIS_TO_INTERNALmaps constructor/user coordinates(x, y)into internal numerator coordinates(a, b).INTERNAL_TO_BASISandINTERNAL_TO_BASIS_DENmap internal numerator coordinates back to public basis coordinates.
This is mainly useful when the natural mathematical notation for a type is not the raw 1, √D basis.
Eisenstein integers are the motivating example. Users write them as a + bω, where QuadraticRing(-3) as
So eisensteinint(x, y) converts from the public ω-basis to the internal numerator basis as:
x + yω = ((2x - y) + y√-3) / 2
Example:
from quadint.eisenstein import eisensteinint
z = eisensteinint(2, 3)
print(z) # (2+3ω)
print(z.real) # 2
print(z.omega) # 3
print(z.basis) # (2, 3)
print(tuple(z)) # (2, 3)
# Internal numerator coordinates are still available, but usually only useful
# for implementing rings/subclasses or debugging low-level arithmetic.
print(z.a, z.b, z.ring.den) # 1 3 2Prefer basis, basis_a, basis_b, and type-specific aliases such as real / omega when presenting values to users. Prefer the internal .a and .b fields only when implementing arithmetic, division, factorization, or another low-level ring operation.
quadint.sums provides small number-theory helpers for decomposing primes and integers into non-negative integer solutions of:
x^2 + d*y^2 = n
The default d=1 gives the classic sum-of-two-squares problem.
from quadint.sums import decompose_prime, decompose_number
print(decompose_prime(19889))
# (17, 140)
print(decompose_number(19890))
# {(69, 123), (57, 129), (3, 141), (87, 111)}Use d to solve related forms:
from quadint.sums import decompose_prime, decompose_number
print(decompose_prime(19, d=3))
# (4, 1) because 4^2 + 3*1^2 == 19
print(decompose_number(12, d=3, no_trivial_solutions=False))
# {(0, 2), (3, 1)} because 0^2 + 3*2^2 == 12 and 3^2 + 3*1^2 == 12Return a non-negative pair (x, y) for a prime-like input where:
x^2 + d*y^2 = den^2 * p
For normal public use, leave den=1. Passing den=2 is mainly useful when working with denominator-2 quadratic orders, where the returned pair is in numerator coordinates.
from quadint.sums import decompose_prime
print(decompose_prime(5))
# (1, 2)
print(decompose_prime(7, d=3))
# (2, 1)
print(decompose_prime(2, d=7, den=2))
# (1, 1) because 1^2 + 7*1^2 == 2^2 * 2Return all canonical non-negative integer pairs (x, y) satisfying:
x^2 + d*y^2 = n
from quadint.sums import decompose_number
print(decompose_number(325, no_trivial_solutions=False))
# {(1, 18), (6, 17), (10, 15)}decompose_number accepts either an integer or a precomputed factorization dictionary:
from quadint.sums import decompose_number
print(decompose_number({2: 1, 3: 2, 5: 1, 13: 1, 17: 1}))
# same result as decompose_number(19890)Useful options:
d=1by default; use another positive integer forx^2 + d*y^2 = n.no_trivial_solutions=Trueby default; set it toFalseto include solutions with a zero coordinate and symmetricd=1solutions such as(0, 2)forn=4.check_count=Nreturns an empty set early when the predicted number of solutions is belowN.
Every solution is found, for every d. With the class-number-one values d in {1, 2, 3, 7, 11, 19, 43, 67, 163} (and their multiples by squares), each solution is multiplied out of elements with prime norms, one for each prime factor of n. Any other d has primes with no element of that norm: neither 3 nor 7 is x^2 + 5*y^2, but 21 == 4^2 + 5*1^2 == 1^2 + 5*2^2. Those go through the ideals of norm n instead, which is slower.
There is also a small companion module for decomposing Eisenstein norms of the form:
a^2 - a*b + b^2 = n
This is mostly a fun helper built on the Eisenstein integer machinery rather than a central part of the package. It mirrors the main quadint.sums API:
from quadint.sums.eisenstein import decompose_prime, decompose_number
print(decompose_prime(7))
# (1, 3) # because 1^2 - 1*3 + 3^2 == 7
print(decompose_number(91, no_trivial_solutions=False))
# {(1, 10), (5, 11)}, the canonical pairs (a, b) with a^2 - a*b + b^2 == 91no_trivial_solutions=True filters the obvious square-like rays where a == 0, b == 0, or a == b. As with the rest of quadint.sums, a factorization dictionary may be passed instead of an integer.
complexint(a: int = 0, b: int = 0)eisensteinint(a: int = 0, b: int = 0)wherea + bωdualint(a: int = 0, b: int = 0)splitint(a: int = 0, b: int = 0)QuadraticRing(D: int, den: int | None = None)- If
denis omitted (None), it defaults to2whenD % 4 == 1, otherwise1. Passingden=2for any otherDraisesValueError.
- If
-
Q(a: int = 0, b: int = 0) -> QuadInt(the numerators of$(a + b\sqrt{D}) / \mathrm{den}$ , so withden=2they must have the same parity) -
Q.from_ab(a: int, b: int) -> QuadInt($a + b\sqrt{D}$ , whateverdenis) -
Q.from_obj(x) -> QuadInt(embedint/float, andcomplexonly in the Gaussian integers) -
Q.ideal(*generators),Q.prime_ideals_over(p),Q.class_group,Q.class_number(maximal orders) -
Q.fundamental_unit()(real rings),Q.elements_with_norm(n),Q.has_element_with_norm(n) -
Q.discriminant(),Q.supports_division(),Q.supports_factorization()
x.conjugate()abs(x)(norm)x.trace(x + x.conjugate(), as anint; everyxis a root ofx**2 - x.trace*x + abs(x))x.units(finite torsion unit subgroup exposed as a tuple)x.is_unit,x.is_irreduciblex.content()x.factor_detail()(returnsFactorization(unit, primes))x.factor()(returns plaindict[QuadInt, int])divmod(x, y),x // y,x % y(where supported)x.gcd(y),x.xgcd(y)(returns(g, s, t)withs*x + t*y == g),x.inv_mod(m),pow(x, e, m)(where supported)x.exact_div(y)(the quotient ifydividesx, otherwiseNone),y.divides(x)- Iteration/indexing over the basis coordinates:
list(x),x[0],x[1]
I.norm,x in I,I + J(their gcd, in a maximal order),I * J,I**k,I // J(exact quotient),I.divides(J),I.conjugate()I.is_prime,I.factor()(prime ideals, with repeats),I.is_principal,I.principal_generator()
decompose_prime(p: int, d: int = 1, den: int = 1) -> tuple[int, int]decompose_number(n: int | dict[int, int], d: int = 1, check_count: int | None = None, *, limited_checks: bool = False, no_trivial_solutions: bool = True) -> set[tuple[int, int]]