Euclidean Division

Let aZa ∈ Z and bZb ∈ Z be two integers with b0b \neq 0. Then there is always another integer mZm ∈ Z and a natural number rNr ∈ N, with 0r<b0 ≤ r < |b| such that the following holds:

a=mb+ra = m · b + r

This decomposition of a given bb is called Euclidean Division, where aa is called the dividend, bb is called the divisor, mm is called the quotient and rr is called the remainder. It can be shown that both the quotient and the remainder always exist and are unique, as long as the divisor is different from 0.

Notation: Suppose that the numbers a,b,ma, b, m and rr satisfy above equation. We can then use the following notation for the quotient and the remainder of the Euclidean Division as follows:

a div b:=m,a mod b:=ra \text{ div } b := m, a \text{ mod } b := r

We also say that an integer aa is divisible by another integer bb if a mod b=0a \text{ mod } b = 0 holds. In this case, we write bab|a, and call the integer a div ba \text{ div } b the cofactor of bb in aa.

The Euclidean Algorithm

The greatest common divisor of two non-zero integers aa and bb is defined as the largest non-zero natural number dd such that dd divides both aa and bb, that is, dad|a as well as dbd|b are true. We use the notation gcd(a,b):=dgcd(a, b) := d for this number. Since the natural number 1 divides any other integer, 1 is always a common divisor of any two non-zero integers, but it is not necessarily the greatest.

A common method for computing the greatest common divisor is the so-called Euclidean Algorithm:

def gcd(a, b):
    (r, rr) = (a, b)
    while r % rr != 0:
        (r, rr) = (rr, r % rr)
    return rr

Sage example:

a.gcd(b)

Complexity: O(logmin(a,b))O(\log{\min(a, b)})

The Extended Euclidean Algorithm

The Extended Euclidean Algorithm is a method for calculating the greatest common divisor of two natural numbers aa and bNb \in N, as well as two additional integers s,tZs,t ∈ Z, such that the following equation holds:

gcd(a,b)=sa+tb.gcd(a, b) = s · a + t · b.
def xgcd(a, b):
    (r, rr) = (a, b)
    (s, ss) = (1, 0)
    (t, tt) = (0, 1)
    while r % rr != 0:
        q = r // rr
        (r, rr) = (rr, r - q * rr)
        (s, ss) = (ss, s - q * ss)
        (t, tt) = (tt, t - q * tt)
    return (rr, ss, tt)

Sage example:

a.xgcd(b)

Complexity: O(logmin(a,b))O(\log{\min(a, b)})

Last updated