Enumerate by the hypotenuse and test finitely many shorter legs:
primitiveTriples :: [(Integer, Integer, Integer)]
primitiveTriples =
  [(a, b, c) |
     c <- [1..],
     b <- [1..c-1],
     a <- [1..b-1],
     a*a + b*b == c*c,
     gcd a (gcd b c) == 1]
The equality selects Pythagorean triples, and the greatest common divisor test makes them primitive. The bounds enforce , removing the duplicate obtained by exchanging the legs. Each fixed has a finite search, so the outer loop gives ascending hypotenuse order and reaches every qualifying triple. Infinite families supplied by Euclid's formula ensure that the stream has arbitrarily many outputs. Its first five entries are
[(3,4,5),(5,12,13),(8,15,17),(7,24,25),(20,21,29)]
Using Integer avoids overflow in the squared values. The construction prioritizes a direct correctness argument; it does not claim an optimal enumeration cost.
For integers not both zero, replace them first by their absolute values, then repeat integer division:
while b != 0:
    (a,b) := (b, a mod b)
return a
This is the Euclidean algorithm. Its loop invariant is that equals the original greatest common divisor. When , the new remainder lies in , so is a strictly decreasing nonnegative loop variant. At termination, , proving correctness, including the case where one original input is zero.
Use the iterative Euclidean algorithm for a nonnegative numerator and positive denominator:
function GCD(m,n): integer
    a := m
    b := n
    while b != 0 do
        r := a mod b
        a := b
        b := r
    return a

procedure Reduce(var m,n)
    require m >= 0 and n > 0
    d := GCD(m,n)
    m := m div d
    n := n div d
The loop invariant is with . The nonnegative loop variant is : when positive, the new remainder is strictly smaller. Thus the final is the positive greatest common divisor. Dividing both numerator and denominator by it preserves the rational number and makes them coprime. The stated proper fraction case is included, but the same code works for every nonnegative numerator, a fact useful in part (d). In particular, zero reduces to .
Add the unit fractions one at a time, reducing after each addition:
procedure toRat(e; var m,n)
    require 0 <= e.i <= N and every stored denominator is positive
    m := 0
    n := 1
    j := 0
    while j < e.i do
        q := e.x[j]
        m := m*q+n
        n := n*q
        Reduce(m,n)
        j := j+1
The loop invariant is that is the reduced fraction equal to the sum of the first terms, with . The update is exactly , and the greatest common divisor reduction preserves it. The loop variant decreases to zero. The empty sum gives .
An arbitrary stored Egyptian sum can be at least one, so this uses the broader nonnegative-numerator contract of the implementation in part (a), not an unjustified assumption that every intermediate fraction is proper.
Divide numerator and denominator by their positive greatest common divisor, then fix the sign:
PROCEDURE reduce(x: rational);
VAR g: INTEGER;
BEGIN
  ASSERT(x.den # 0);
  g := gcd(ABS(x.num),ABS(x.den));
  x.num := x.num DIV g; x.den := x.den DIV g;
  IF x.den < 0 THEN
    x.num := -x.num; x.den := -x.den
  END
END reduce;
The denominator condition ensures , including when the numerator is zero. Dividing both components by the same nonzero integer preserves the fraction, and the final simultaneous sign change preserves it again. The resulting numerator and denominator are coprime; for zero the denominator becomes one.
Choose the representative . Since is prime and does not divide , their greatest common divisor is one. The extended Euclidean algorithm gives the Bezout identity
for some integers . Reducing modulo gives , so the residue class of is a multiplicative inverse of . The argument uses the nonzero condition to exclude the only residue with greatest common divisor .
Use the remainder form of the Euclidean algorithm to compute the greatest common divisor, then divide both components of the fraction by it:
def Reduce(num: Int, den: Int): (Int, Int) = {
  require(0 <= num && num < den)
  var a = den
  var b = num
  while (b != 0) {
    val r = a % b
    a = b
    b = r
  }
  (num / a, den / a)
}
The loop invariant is , , and . Initially it holds by symmetry of the greatest common divisor. For , the integer division identity , with , shows that and have exactly the same common integer divisors. Thus the update preserves the loop invariant. The loop variant is the nonnegative integer , which strictly decreases on each iteration. At exit , so . Dividing by preserves the rational number and makes the returned components coprime. In particular, zero is returned as . No multiplication is needed, and all remainders remain within the original nonnegative Int range.
Maintain an accumulated array of denominators and an exact remaining fraction. The usual greedy algorithm can require a denominator larger than Int.MaxValue, even for an input with Int components. The following implementation uses arbitrary-precision integers internally. If that representational limit is reached, it returns the always-valid alternative consisting of num copies of . Repeated denominators are permitted by the given Egyptian fraction representation.
def fromRat(num: Int, den: Int): Array[Int] = {
  require(0 <= num && num < den)
  val start = Reduce(num, den)
  var n = BigInt(start._1)
  var d = BigInt(start._2)
  var e = Array.empty[Int]
  while (n > 0) {
    val q = (d + n - 1) / n
    if (!q.isValidInt) return Array.fill(num)(den)
    e = e :+ q.toInt
    val nextN = n * q - d
    val nextD = d * q
    val g = nextN.gcd(nextD)
    n = nextN / g
    d = nextD / g
  }
  e
}
The loop invariant is , , all entries of e are positive, and
Appending and replacing the residual by preserves this equality; division by the greatest common divisor preserves the residual's value. The loop variant is , by the proof in part (b). If nextN is zero, its greatest common divisor with nextD is nextD, giving residual . On normal exit the residual is zero and the returned array has exactly the required value. On the early-return branch, num copies of have that same value directly; the partial greedy Egyptian fraction expansion is discarded. num=0 returns an empty array.
The fallback is a correctness provision for the fixed result type, not an efficiency claim: a large repeated-term array can be impractical. An array of arbitrary-precision integers would retain the greedy Egyptian fraction expansion without this fallback. Allocation, as with any output-producing program, requires enough available memory. The BigInt remainder, greatest common divisor and checked conversion operations are documented in [ref].
Let , and write , with positive integers . If an integer divided both and , then would divide both and , contradicting the maximality of their greatest common divisor . Thus . Equivalently, Bézout's identity for can be divided by to express as an integer combination of .
The Euclidean algorithm repeatedly replaces by , where the new remainder lies between and . Common divisors are unchanged by this subtraction, and decreasing positive remainders ensure termination. The last nonzero remainder is the greatest common divisor.
The extended Euclidean algorithm also tracks coefficients , beginning with coefficient pairs and and applying the same subtraction to the pairs. This invariant produces Bézout coefficients for the last nonzero remainder. Here the divisions are
Back substitution gives
Thus , with and in Bézout's identity.
Pollard's rho algorithm 2026-10-20
An integer factorization algorithm that iterates a simple map such as and searches for a nontrivial greatest common divisor of and the difference of two iterates. A collision modulo an unknown prime factor can reveal that factor before a collision modulo . A cycle detection schedule such as Floyd's cycle-finding algorithm limits the number of stored iterates. Unsuccessful choices of seed or map can be retried.
Polynomial division Created 2026-09-24 Updated 2026-10-18
Polynomial division separates a polynomial into a multiple of a chosen divisor and a smaller polynomial remainder. Given over a field , with , there are unique polynomials satisfying
Here is the polynomial quotient. The bound concerns polynomial degree, rather than the sizes of the coefficients.[ref]
For an original example over the rational numbers, take
Polynomial long division first cancels by subtracting :
Subtracting one more copy of cancels :
Thus
The final polynomial remainder has polynomial degree one, below the divisor's polynomial degree two. Multiplying out the last identity checks every coefficient, including the constant term .
Figure 1.
Polynomial long division cancels the cubic and quadratic terms in two steps, recording and
. Details.
The polynomial degree bound makes this decomposition useful: it replaces a potentially long polynomial with a short polynomial remainder whenever multiples of can be discarded. At any root of a polynomial of , those multiples vanish under polynomial evaluation. Repeated polynomial division also drives the Euclidean algorithm for finding a greatest common divisor of polynomials.
The coefficient setting matters. Over a commutative ring, the same existence and uniqueness hold when the divisor's leading coefficient is a unit in a ring. A monic polynomial therefore works over the integers, even though they do not form a field; monic polynomial division over a ring explains why zero divisors cause no difficulty in that case.[ref]
A nonzero divisor alone is insufficient over the integers. Dividing by with an integer polynomial quotient and a constant polynomial remainder would require for an integer , which is impossible. Over the rational numbers the division instead gives
The obstruction is the nonunit leading coefficient . This example separates existence from uniqueness: over an integral domain, the polynomial degree argument still makes any admissible pair unique, if it exists.
Let with primes and . quadratic reciprocity makes three a square modulo ; choose and impose , by the Chinese remainder theorem. The curve has good reduction at both primes. Indeed its discriminant is ; the first condition could make a factor vanish only at or 11, while the second gives and the given residue class excludes .
Doubling gives . This vanishes modulo and equals one modulo . Modulo one also has , so and is the identity. Modulo the addition is finite. Thus computing modulo encounters a denominator whose greatest common divisor with is exactly , revealing the factor. The numerator difference is minus two modulo , so the failed inverse cannot be cancelled. This is a construction of successful elliptic curve method data from prescribed local group behavior.
Prime number Created 2026-09-24 Updated 2026-10-13
A prime number is a positive integer whose only positive divisors are and . The first ten prime numbers are . In contrast, is a composite number because it has a positive divisor strictly between one and itself. The integer one is neither a prime number nor a composite number: the lower bound is part of the definition. Equivalently, the divisor function satisfies for a prime number, whereas and for every composite number .
Prime numbers are the building blocks of positive integers under multiplication. The fundamental theorem of arithmetic says that every integer greater than one is a product of prime numbers, with a unique collection of factors when their order is ignored. For example, and . Their common factors reveal the greatest common divisor , and the combined maximum powers reveal the least common multiple . A complicated divisibility question becomes a comparison of prime exponents.
There is also a useful finite test. If a composite number equals with , then . Therefore some prime factor is at most , and trial division only needs to check prime numbers up to that square root. For , checking suffices; none divides , so it is a prime number. For , the same test finds , giving . To find many prime numbers together, the sieve of Eratosthenes reuses the work by marking multiples.
The division with remainder calculations for make the test explicit:
Since , these are all the prime numbers at most its square root, and every remainder is nonzero. Thus the calculation certifies a prime number, without testing the integers individually. In contrast, gives a prime factor and proves that is a composite number.
The definition has a long history. Book VII of Euclid's Elements distinguishes prime numbers from composite numbers through their possible measures; Book IX, Proposition 20 establishes that no finite list exhausts the prime numbers. The modern argument under Euclid's theorem needs only divisibility, so it proves an infinite conclusion without estimating how frequently prime numbers occur. [ref] [ref].
Prime omega function Created 2026-09-28 Updated 2026-10-13
The prime omega function counts the distinct prime factors of a positive integer , so it is the cardinality of the prime support of an integer . For a prime factorization with distinct prime numbers and positive exponents,
At there are no prime factors, so the empty sum gives . The total number of prime factors instead gives . [ref]
For , the prime support of an integer is and . The comparison examples give , and . Raising an existing prime factor to a higher power does not affect the prime omega function: for a prime number and . Thus the prime omega function is a strongly additive arithmetic function, with
The reason is that coprime integers have disjoint prime supports of an integer. For arbitrary positive integers, their prime support of an integer combines by set union, and the shared prime factors are exactly those of the greatest common divisor. Counting this set union gives the more general identity
For , , both prime supports of an integer are and , so . In particular : the prime omega function is not a completely additive arithmetic function.
The prime omega function is useful for counting choices involving distinct prime factors. Every squarefree divisor of chooses a subset of its prime support of an integer, so there are squarefree divisors. For , this gives , namely . Also , because the radical of an integer keeps exactly that prime support of an integer. The total number of prime factors records what this count discards, and the two counts agree exactly on squarefree integers.
A primitive Diophantine solution is an integer tuple satisfying the equation whose coordinates have greatest common divisor one. For homogeneous equations, this removes common integer scale factors.
Primitive lattice element Created 2026-10-06 Updated 2026-10-14
A nonzero element of a free abelian group is primitive when it is part of an integral basis, equivalently when some homomorphism to takes it to one. Its coordinates have greatest common divisor one. This lattice meaning differs from a primitive homology class in the coalgebra sense.
A Pythagorean triple whose coordinates have greatest common divisor 1. Its two legs have opposite integer parity, and every Pythagorean triple is a unique positive integer multiple of a primitive Pythagorean triple up to the ordering of its legs.