Let and . Applying polynomial long division gives the euclidean algorithmThus their polynomial greatest common divisor is , up to a nonzero constant factor. Their unique common root of a polynomial is therefore
The euclidean algorithm computes the greatest common divisor of two integers by repeated division with remainder. Start with , , interchanging them if necessary, and repeatedly writeuntil a zero remainder occurs. The positive remainders strictly decrease, so the process terminates. At each step the common divisors of are exactly the common divisors of , because . HenceIf one input is zero, the answer is the absolute value of the other; the usual convention sets . Back-substitution also expresses the greatest common divisor as an integer linear combination of the inputs, as in Bézout's identity.
Let be any positive integer. If divides and , it divides the integer linear combination . Conversely, if divides and , it divides . Thus and have exactly the same positive common divisors. Their greatest elements coincide:This greatest common divisor invariance is the step behind the Euclidean algorithm; it does not require , although that additional bound ensures the algorithm terminates. If the convention permits , the same argument works and for .
Back-substitute in the Euclidean algorithm to obtain an integer linear combination:Multiplying by gives the particular solution of the linear Diophantine equation. Subtracting it from any other solution and dividing by givesThe integers and are coprime, so divides . Writing forces . Conversely these expressions satisfy the original equation for every integer . Thus all solutions of a linear Diophantine equation here are
The successive division with remainder steps of the Euclidean algorithm areEach step preserves the greatest common divisor by part (a). The final nonzero remainder is , so
Back-substitution in the Euclidean algorithm gives the Bezout identityMultiplying by five produces a particular solution . Since and are coprime integers, all solutions of the linear Diophantine equation areReplacing by gives the smaller equivalent starting solutionIndeed . Conversely, subtracting this solution from any other gives . Coprimality forces to divide , and then is the corresponding multiple of . This proves completeness of the family.
An irreducible polynomial has positive degree, so its ideal is proper: otherwise would contradict degrees. Every nonzero class has a representative not divisible by . Irreducibility gives , and the Euclidean algorithm supplies polynomials with . Passing to the quotient gives . Thus the quotient is a nonzero commutative ring in which every nonzero element has an inverse, hence a field. Constants embed injectively because no nonzero constant lies in the positive-degree ideal .
In Pollard's p-1 algorithm, a large exponent containing many small factors makes divisible by a prime factor whose predecessor divides , by Fermat's little theorem. A greatest common divisor with the number being factored can then separate that prime factor from the others.
Choose base and build factorial exponents using modular exponentiation. The successive exponents , , and giveThe first two greatest common divisors are . At the next step the Euclidean algorithm givesHenceHere the element order of modulo is , which divides , even though does not divide . The algorithm only needs the element order to divide the chosen exponent; divisibility by the full predecessor is a sufficient condition, not a necessary one.
Complete the square to obtain the equivalent quadratic congruenceHere : the Euclidean algorithm has successive nonzero remainders . If this modular congruence had a solution, the Jacobi symbol would be , since a square coprime to an odd modulus has Legendre symbol at every prime factor. Calculate instead, using Jacobi reciprocity and reduction of numerators,Therefore there is no solution. This obstruction does not require a separate primality test for ; the Jacobi symbol suffices.
Multiplication, followed by induction and inversion for negative powers, givesIf , apply Euclidean division to write with . Choose , so . This is one step of the Euclidean algorithm implemented by a determinant-one row operation.
The second coordinate after two iterations satisfieswhenever those two divisions are needed, by the same remainder bound, now applied to . Let . If the Euclidean algorithm has not already stopped after iterations, then its positive second coordinate is at most : for ,For the original is already . A second coordinate of requires just one more division. ConsequentlyThis removes dependence on the potentially much larger input . It improves the scale to one involving only the smaller input; the rounded numerical bound need not be smaller for every pair. One may always take the minimum of the bounds in (ii) and (iii).
Count the final division producing zero as an iteration, and let the total be . The terminal product alone gives no useful bound. Instead apply (i) to each nonterminal product, which is a positive integer and hence at least .
If , the penultimate product satisfiesAs is an integer, this impliesFor , the same bound holds since implies . In particular the Euclidean algorithm uses divisions, in big O notation. The convention that includes the final zero-producing division explains the one-step offset in the argument.
Use the Euclidean algorithm with floor quotient and nonnegative remainder, including for a negative numerator:For , Euclidean division gives with . If , the singleton
PROCEDURE rat2cf(n, d: INTEGER): fraction;
VAR q, r: INTEGER; p: fraction;
BEGIN
q := n DIV d; r := n MOD d;
NEW(p); p.head := q; p.tail := NIL;
IF r # 0 THEN p.tail := rat2cf(d, r) END;
RETURN p
END rat2cf;[q] is exact. Otherwiseso the recursive tail represents . Its numerator is positive and greater than its denominator, so every tail head is a positive integer. The new denominator is strictly smaller than , proving algorithm termination by descent through the positive integers.The returned list represents exactly . For example gives
[-3,1,2]; truncating negative division toward zero would violate the required positivity of the tail. There are Euclidean algorithm steps, with output allocation and recursive stack depth linear in the number of generated nodes.Append each quotient directly to the output linked list, retaining a pointer to its last node. The nodes are required output; auxiliary variables remain simple integers and pointers.At the start of each iteration,
PROCEDURE rat2cf(n, d: INTEGER): fraction;
VAR first, last, p: fraction; q, r: INTEGER;
BEGIN
first := NIL; last := NIL;
REPEAT
q := n DIV d; r := n MOD d;
NEW(p); p.head := q; p.tail := NIL;
IF first = NIL THEN first := p
ELSE last.tail := p
END;
last := p;
n := d; d := r
UNTIL d = 0;
RETURN first
END rat2cf;d is positive, and the output prefix consists exactly of the quotients already obtained by the Euclidean algorithm. last points to its final node, or both first and last are null when the prefix is empty. The current ratio n/d is the unexpanded tail of the original continued fraction. The quotient/remainder step extends that prefix by the same value as the recursive version, then replaces the unexpanded ratio by its reciprocal residual tail. If the remainder is zero, no tail remains and the loop stops before another division.The loop variant is the positive current denominator, which strictly decreases after each nonfinal iteration. The input denominator is positive, so at least one node is allocated, including for zero or an integral ratio. This is the same exact conversion with auxiliary space, excluding the returned list, and no input mutation.
Count element reads and writes, ignoring simple-variable operations. A swap of distinct entries makes two reads and two writes, hence four expensive accesses. For , the three-reversal method therefore costsHere if and are both even, and otherwise.
For either block-exchange version, let , , and let count element swaps. The recurrence is and, when the lengths differ,The Euclidean algorithm preserves under this subtraction. Induction on therefore yieldsThus both block-exchange methods cost accesses, no more than the three-reversal method. Their element-access counts are identical; the iterative one avoids the recursive stack. For example a half-length rotation uses swaps instead of approximately reversal swaps.
Each single-place pass in part (iv) reads every entry once and writes every entry once, costing accesses. For , its accesses beat the block method's for and tie for . For the block method costs strictly less than . All three methods as written return without accesses for or . Repeated shifting can take quadratic time; the reversal and block methods take linear time. These comparisons concern the specified implementations, not a more general cycle-decomposition rotation using several disjoint cycles.
Normalize the amount to , with ; negative then naturally denotes a right rotation. When , return without touching the elements. Otherwise the map has disjoint permutation cycles, each of length . Use representatives :The conditional calculation of
PROCEDURE RotateLeft(k: INTEGER);
VAR r, g, x, y, h, s, j, next: INTEGER; saved: T;
BEGIN
r := k MOD N;
IF r # 0 THEN
x := N; y := r;
WHILE y # 0 DO h := x MOD y; x := y; y := h END;
g := x; s := 0;
WHILE s < g DO
saved := a[s]; j := s;
IF j >= N-r THEN next := j-(N-r) ELSE next := j+r END;
WHILE next # s DO
a[j] := a[next]; j := next;
IF j >= N-r THEN next := j-(N-r) ELSE next := j+r END
END;
a[j] := saved; s := s+1
END
END
END RotateLeft;next implements addition modulo without first forming a possibly overflowing j+r. Oberon's MOD with positive divisor supplies the nonnegative remainder. The first loop is the Euclidean algorithm, with loop invariant and decreasing nonzero remainder.For the outer loop, cycles with representatives below
s are complete and every other cycle retains its original values. In one cycle, write . The inner loop invariant is saved = A[s], , and for , with the remaining sources still untouched. When the next index returns to s, the saved value closes the cycle. The cycle length is : writing and with , the least positive with is . Each residue class modulo is one cycle, justifying the chosen representatives.Every element is read once and written once: element accesses, compared with for repetitions of part (b). The zero rotation uses none. The running time is and auxiliary space is constant; the original array is proof notation, not a copy made by the program.
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 aThis 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.
The Euclidean algorithm givesThus the greatest common divisor is . Back-substitution, as in the extended Euclidean algorithm, givesHence , with and .
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 dThe 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 .