{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# The Euclidean Algorithm\n",
"\n",
"This worksheet provides an introduction to the Euclidean algorithm—in its most basic form, a way to find the largest possible number that evenly divides two other numbers.\n",
"\n",
"Knuth says the Euclidean algorithm is \"the oldest nontrivial algorithm that has survived to the present day\".\n",
"\n",
"The algorithm has a huge number of applications, from cryptography to coding theory to solving linear equations over the integers."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Greatest Common Divisor"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The _greatest common divisor_ (gcd) of two integers is the largest number that \"divides\" each of them. For example, the greatest common divisor of 15 and 24 is 3.\n",
"\n",
"The (positive) divisors of 15 are 1, 3, 5, and 15. The (positive) divisors of 24 are 1, 2, 3, 4, 6, 8, 12, 24. These can be computed with the `divisors` command:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"show(divisors(15))\n",
"show(divisors(24))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `gcd` command computes the gcd of two numbers:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"gcd(15, 24)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also compute the gcd of two polynomials:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"R. = ZZ[]\n",
"a = x^4-x^3-3*x^2+x+2\n",
"b = x^3-4*x^2+x+6\n",
"g = gcd(a, b)\n",
"show(a)\n",
"show(b)\n",
"show(g)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To double-check this computation, we could also explicitly factor the polynomials and look for their common factors:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"show(factor(a))\n",
"show(factor(b))\n",
"show(factor(g))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Computation of gcd"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"How should the gcd of two numbers (or polynomials) be computed? The most straightforward way of finding all the divisors of the numbers and then selecting the greatest is quite inefficient and not a good way except in small cases.\n",
"\n",
"Fortunately, the Euclidean algorithm provides a different and efficient way of computing greatest common divisors.\n",
"\n",
"It is based on the following simple identity:\n",
"\n",
"$$ \\gcd(a, b) = \\gcd(a, b-a) \\notag $$\n",
"\n",
"This holds as a result of the property that any number which divides both $a$ and $b$ also divides their difference."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### How does this help?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"At first this might look useless, since it would seem that we would need to already know how to compute gcds in order to make use of it.\n",
"\n",
"However, it suggests a recursive algorithm. Suppose $b>a>0$ so that $b-a$ is positive but smaller than $b$. In this sense computing $\\gcd(a,b-a)$ is simpler than computing $\\gcd(a,b)$.\n",
"\n",
"Example: $\\gcd(15,24)=\\gcd(15,9)=\\gcd(9,6)=\\gcd(6,3)=\\gcd(3,3)=\\gcd(3,0)=3$\n",
"\n",
"Repeatedly subtracting the larger from the smaller number must eventually reach 0 and we know that $\\gcd(x,0)=x$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### A closer look"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Repeated subtractions are wasteful. For example:\n",
"\n",
"$$\\gcd(1,1000)=\\gcd(1,999)=\\gcd(1,998)=\\dotsb=\\gcd(1,1)=\\gcd(1,0)=1 \\notag $$\n",
"\n",
"A better idea: subtract off as many multiples of $a$ as possible at each step. In other words, we use the identity\n",
"\n",
"$$ \\gcd(a,b) = \\gcd(a, b-qa) \\notag $$\n",
"\n",
"where $q$ is as large as possible so that $b-qa$ remains positive."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Look familiar?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The largest value of $q$ for which $b - qa$ is positive is $q=\\lfloor b/a\\rfloor$ (the _floor_ of $b/a$).\n",
"\n",
"Then $b - qa$ is just the remainder of $b$ divided by $a$ (commonly denoted by $b\\bmod a$). In the worksheet on basic algebraic operations we already saw how to compute this."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Basic Euclidean Algorithm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's basic pseudocode for the Euclidean algorithm on nonnegative $b\\geq a$:\n",
"\n",
" if a = 0 then\n",
" return b\n",
" # Compute remainder of b divided by a\n",
" r = b % a\n",
" return gcd(r, a)\n",
" \n",
"In fact, this even works if $a>b$, since then $r$ will be set to $b$ and $\\gcd(b,a)$ will be returned—in other words, the order of the parameters will be swapped so the first parameter is larger."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Sage implementation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Compute the gcd of a and b\n",
"def my_gcd(a, b):\n",
" if a == 0:\n",
" return b\n",
" return my_gcd(b % a, a)\n",
" \n",
"my_gcd(15, 24)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Iterative Euclidean Algorithm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The above algorithm can also be written iteratively to avoid recursion.\n",
"\n",
"We start by setting $r_0:=a$, $r_1:=b$ and then iteratively compute new remainders via\n",
"\n",
"$$ r_{i+1} := r_{i-1} \\bmod r_i \\notag . $$\n",
"\n",
"It follows that $\\gcd(r_0,r_1)=\\gcd(r_1,r_2)=\\dotsb=\\gcd(r_l,r_{l+1})$ and once a remainder in this sequence becomes 0 we can stop and return the last nonzero entry."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Sage implementation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Compute the sequence of remainders in the Euclidean algorithm on (a, b)\n",
"def remainder_sequence(a, b):\n",
" r = [a, b]\n",
" while r[-1] != 0:\n",
" r.append(r[-2] % r[-1])\n",
" return r\n",
"\n",
"show(remainder_sequence(15, 24))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Big examples"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The beauty of this algorithm is that works well on very large numbers."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Compute the remainder sequence of two primes with 50 bits\n",
"show(remainder_sequence(random_prime(2^50), random_prime(2^50)))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = (2^200).next_prime()\n",
"b = (2*a).next_prime()\n",
"c = (2*b).next_prime()\n",
"show([a, b, c])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"show([a*b, b*c])\n",
"my_gcd(a*b, b*c)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"show(remainder_sequence(a*b,b*c))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### A polynomial example"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The same basic algorithm works for polynomials as well. Recall that in this case the \"size\" of a polynomial is given by its degree. In this case, the remainders will form a sequence that strictly decrease in degree.\n",
"\n",
"Note that the gcd is not unique here: if $g$ is a gcd then any constant multiple of $g$ will also be a gcd. To have a single canonical answer, we can enforce uniqueness by specifying that the leading coefficient of a gcd is 1."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Compute with polynomials with rational coefficients\n",
"R. = QQ[]\n",
"a = x^4-x^3-3*x^2+x+2\n",
"b = x^3-4*x^2+x+6\n",
"\n",
"# Compute remainder sequence of a and b in R = QQ[x]\n",
"def remainder_sequence_poly(a, b):\n",
" r = [a, b]\n",
" while r[-1] != 0:\n",
" g = r[-2] % r[-1]\n",
" if g != 0:\n",
" g = g/g.leading_coefficient()\n",
" r.append(g)\n",
" return r\n",
"\n",
"# Compute normalized gcd of a and b\n",
"def my_gcd_poly(a, b):\n",
" g = remainder_sequence_poly(a, b)[-2]\n",
" return g/g.leading_coefficient()\n",
"\n",
"show(a)\n",
"show(b)\n",
"show(remainder_sequence_poly(a, b))\n",
"show(my_gcd_poly(a, b))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# A larger example - note that the coefficients of the remainder polynomials may not be integers\n",
"a = (x+1)^2*(x-1)^5\n",
"b = (x+1)^5*(x-1)^2\n",
"show(remainder_sequence_poly(a, b))\n",
"show(my_gcd_poly(a, b))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"show(my_gcd_poly(a, b) == (x+1)^2*(x-1)^2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Algorithm Analysis"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We saw that Euclid's algorithm seems fast, but _how_ fast?\n",
"\n",
"Suppose that $a$ and $b$ have length at most $n$. On each iteration the remainders decrease so all remainders have length at most $n$. Thus the computation of each remainder uses $O(n^2)$ word operations. Since the remainders decrease on each loop iteration there can be at most $n$ iterations. (Or at most $m+1$ iterations, since after the first iteration the remainder will have degree at most $m$.)\n",
"\n",
"Thus, Euclid's algorithm on length $n$ integers requires $O(n^3)$ word operations. Similarly, Euclid's algorithm on degree $n$ polynomials requires $O(n^3)$ coefficient operations.\n",
"\n",
"While this is correct, it is not actually a tight bound: the analysis can be improved. Recall from the previous worksheet that division with remainder on operands of size $n$ and $m$ requires $O((n - m + 1)\\cdot m)$ word/coefficient operations. Say that $c$ is a constant hidden by the O notation, i.e., the remainder can be performed in at most $c\\cdot (n - m + 1)\\cdot m$ operations.\n",
"\n",
"Let $n_i$ denote the size of $r_i$ and say there are up to $l$ iterations of the while loop. The total number of word/coefficient operations used is at most $\\sum_{i=1}^l c\\cdot(n_{i-1}-n_i+1)\\cdot n_i$.\n",
"\n",
"Note that $\\sum_{i=1}^l (n_{i-1}-n_i+1)=n_0-n_l+l\\leq 2\\cdot n$ since each term cancels with the subsequent term and there are at most $n$ iterations of the loop.\n",
"\n",
"Then the total cost is at most\n",
"\n",
"$$ \\sum_{i=1}^l c\\cdot (n_{i-1}-n_i+1)\\cdot n_i \\leq c\\cdot m\\cdot\\sum_{i=1}^l(n_{i-1}-n_i+1) \\leq 2\\cdot c\\cdot n\\cdot m \\notag $$\n",
"\n",
"operations. In other words, a quadratic cost of $O(nm)$ operations."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Extended Euclidean Algorithm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One of the many applications of the Euclidean algorithm is to solve linear equations over the integers—known as linear Diophantine equations.\n",
"\n",
"For example, given integers $a$, $b$, and $d$ can you solve\n",
"\n",
"$$ ax + by = d \\notag $$\n",
"\n",
"for integers $x$ and $y$?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Bézout's identity"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Any common divisor of $x$ and $y$ must also divide $ax$ and $by$, and therefore must divide $ax+by=d$. In particular, the greatest common divisor of $x$ and $y$ must divide $d$ for this equation to have a solution. That is, $d$ being a multiple of $\\gcd(x,y)$ is a _necessary_ condition for this equation to be solvable.\n",
"\n",
"_Bézout's identity_ says that this condition is also a _sufficient_ condition. In other words, Bézout's identity describes exactly when this equation has solutions—namely, exactly when $d$ is a multiple of $\\gcd(a, b)$. In particular, solutions will exist when $d = \\gcd(a, b)$. The _Extended_ Euclidean algorithm (EEA) gives a method that solves this equation.\n",
"\n",
"The EEA performs the same operations as the normal Euclidean algorithm but it also keeps track of additional information. In particular, on the $(i-1)$th loop iteration this extra information is a solution pair $(x,y)$ of the equation\n",
"\n",
"$$ ax + by = r_i . \\tag{$*$} $$\n",
"\n",
"Then the second-last iteration provides a solution of $ax+by =r_{l-1}=d$ (where there are $l$ loop iterations)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Initializing the EEA"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To start off with, note that we can easily find solutions of $(*)$ for the initial values $i = 0, 1$.\n",
"\n",
"In particular, we have\n",
"\n",
"\\begin{align*}\n",
"a\\cdot1+b\\cdot0 &= a = r_0 \\\\\n",
"a\\cdot0+b\\cdot1 &= b = r_1 .\n",
"\\end{align*}\n",
"\n",
"In other words, if $(x_i,y_i)$ denotes a solution to $(*)$ then we can start off with\n",
"\n",
"\\begin{align*}\n",
"(x_0,y_0) &= (1,0) \\\\\n",
"(x_1,y_1) &= (0,1) .\n",
"\\end{align*}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Iteration step in the EEA"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Suppose we are on the $i$th loop iteration of the EEA. On the previous two loop iterations we stored solutions $(x_{i-2},y_{i-2})$ and $(x_{i-1},y_{i-1})$ which satisfy\n",
"\n",
"\\begin{align*}\n",
"ax_{i-2} + by_{i-2} &= r_{i-2} \\\\\n",
"ax_{i-1} + by_{i-1} &= r_{i-1} .\n",
"\\end{align*}\n",
"\n",
"Recall that $r_i = r_{i-2} \\bmod r_{i-1}$ since $r_i=r_{i-2}-qr_{i-1}$ where $q=\\lfloor r_{i-2}/r_{i-1}\\rfloor$. Note that we can take the first of the two equations above and subtract off $q$ copies of the second equation to form the new equation\n",
"\n",
"$$ a (x_{i-2} - qx_{i-1}) + b (y_{i-2} - qy_{i-1}) = r_{i-2} - qr_{i-1} = r_i . \\notag $$\n",
"\n",
"Thus, we set $x_i := x_{i-2} - q x_{i-1}$ and $y_i := y_{i-2} - q y_{i-1}$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Example"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following is a Sage implementation of the EEA (along with printing the sequence of equations produced as output for demonstration). Note that `//` in sage denotes integer division, i.e., `a//b` means $\\lfloor a/b\\rfloor$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Returns integers (x,y) such that a*x+b*y = gcd(a,b)\n",
"def eea(a, b):\n",
" r = [a, b]\n",
" x = [1, 0]\n",
" y = [0, 1]\n",
" print(\"{}*({}) + {}*({}) = {}\".format(a, x[0], b, y[0], r[0]))\n",
" print(\"{}*({}) + {}*({}) = {}\".format(a, x[1], b, y[1], r[1]))\n",
" while r[-1] != 0:\n",
" q = r[-2]//r[-1]\n",
" r.append(r[-2]-q*r[-1])\n",
" x.append(x[-2]-q*x[-1])\n",
" y.append(y[-2]-q*y[-1])\n",
" print(\"{}*{} + {}*{} = {}\".format(a, x[-1], b, y[-1], r[-1]))\n",
" return x[-2], y[-2]\n",
"\n",
"a, b = 15, 24\n",
"x, y = eea(a, b)\n",
"show([x,y])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x*a + y*b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Analysis of the EEA"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The analysis of the EEA proceeds in the same basic way as the analysis of the standard Euclidean algorithm except now there are a few new expressions that add to the cost—in particular, the two new multiplications $qx_{i-1}$ and $qy_{i-1}$.\n",
"\n",
"This is slightly tricky to analyze as the values of $x_i$ and $y_i$ increase in absolute value as $i$ increases. However, one can show that $\\lvert y_i\\rvert\\leq a$ and $\\lvert x_i\\rvert\\leq b$ will hold for all $i$. Thus $y_i$ has length at most $n$ and $x_i$ has length at most $m$ and these bounds will be sufficient in the analysis.\n",
"\n",
"Let $q_i$ denote the value of $q$ on the $i$th iteration. The definition of $q_i$ implies that $\\renewcommand{\\len}{\\operatorname{len}}\\len(q_i)\\leq\\len(r_{i-1})-\\len(r_{i-2})+1$ and using this for $2\\leq i\\leq l$ we derive\n",
"\n",
"$$ \\sum_{i=2}^l \\len(q_i) \\leq \\len(r_1) - \\len(r_l) + l - 1 \\leq 2m \\notag $$\n",
"\n",
"by a similar \"term cancellation\" argument as before.\n",
"\n",
"Since $y_1=1$ the multiplication $q_1\\cdot y_1$ is free.\n",
"The total cost of computing all multiplications $q_i\\cdot y_i$ for $i=2$, $\\dotsc$, $l$ is then\n",
"\n",
"$$ \\sum_{i=2}^l \\len(y_i)\\cdot\\len(q_i) \\leq \\len(a)\\cdot\\sum_{i=2}^l \\len(q_i) \\leq n\\cdot(2m) = 2nm . \\notag $$\n",
"\n",
"The multiplications $q_i\\cdot x_i$ are similarly handled and this gives a total running cost of $O(nm)$ word operations to perform the extended Euclidean algorithm."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Built-in Sage function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sage also provides the built-in function which performs the EEA: `xgcd(a,b)` returns a triple $(g,x,y)$ satisfying $g=xa+yb$ where $g=\\gcd(a,b)$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"xgcd(15,24)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Typical Behaviour\n",
"\n",
"We've seen that the EEA run on two polynomials of degree $n$ will require $O(n^2)$ operations in the coefficient ring—or rather _field_, since the Euclidean algorithm performs division by the leading coefficient of the polynomials in the remainder sequence. This is in order to keep their leading coefficients 1. (Which ensures the leading coefficients are invertible so that the division algorithm works.)\n",
"\n",
"Although this analysis is correct it isn't the entire story, operations in a coefficient field are not always the same difficulty. For example, computing the sum of two single-digit numbers is easier than computing the sum of two million-digit numbers.\n",
"\n",
"Running the Euclidean algorithm on two small random polynomials over the rationals makes this point clear, as the coefficients of the polynomials in the remainder sequence will grow significantly in size, even if the initial coefficients are small integers:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = R(random_vector(ZZ, 12).list())\n",
"b = R(random_vector(ZZ, 12).list())\n",
"show(a)\n",
"show(b)\n",
"show(remainder_sequence_poly(a,b))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similarly, the coefficients in the $x$ and $y$ produced by `xgcd` function will typically grow large, even when the gcd itself is small:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"g, x, y = xgcd(a,b)\n",
"show(x)\n",
"show(y)\n",
"show(a*x+b*y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The methods of _modular arithmetic_ provide a way to better control the size of the coefficients, and in addition provide an algorithm that can compute the gcd of two polynomials in $\\mathbb{Z}[x]$ (instead of in $\\mathbb{Q}[x]$). Modular arithmetic will be the subject of the next topic covered in the course."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "SageMath 9.5",
"language": "sage",
"name": "sagemath"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.4"
},
"latex_envs": {
"LaTeX_envs_menu_present": false,
"autoclose": false,
"autocomplete": false,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": false,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"latex_metadata": {
"author": "Curtis Bright",
"date": "September 19, 2022",
"title": "Computational Mathematics: Handout 03"
}
},
"nbformat": 4,
"nbformat_minor": 4
}