Алгори́тм Евкли́да — эффективный алгоритм для нахождения наибольшего общего делителя двух целых чисел (или общей меры двух отрезков). Алгоритм назван в честь греческого математика Евклида (III век до н. э.), который впервые описал его в VII[1] и X[2] книгах «Начал». Это один из старейших численных алгоритмов, используемых в наше время[3].
В самом простом случае алгоритм Евклида применяется к паре положительных целых чисел и формирует новую пару, которая состоит из меньшего числа и разницы между большим и меньшим числом. Процесс повторяется, пока числа не станут равными. Найденное число и есть наибольший общий делитель исходной пары. Евклид предложил алгоритм только для натуральных чисел и геометрических величин (длин, площадей, объёмов). Однако в XIX веке он был обобщён на другие типы математических объектов, включая целые числа Гаусса и полиномы от одной переменной. Это привело к появлению в современной общей алгебре такого понятия, как евклидово кольцо. Позже алгоритм Евклида был обобщён на другие математические структуры, такие как узлы и многомерные полиномы.
Для данного алгоритма существует множество теоретических и практических применений. В частности, он является основой для криптографического алгоритма с открытым ключом RSA[4], широко распространённого в электронной коммерции. Также алгоритм используется при решении линейных диофантовых уравнений[5], при построении непрерывных дробей[6], в методе Штурма[7]. Алгоритм Евклида является основным инструментом для доказательства теорем в современной теории чисел, например таких как теорема Лагранжа о сумме четырёх квадратов[8] и основная теорема арифметики[9].
История[править | править код]
Древнегреческие математики называли этот алгоритм ἀνθυφαίρεσις или ἀνταναίρεσις — «взаимное вычитание». Этот алгоритм не был открыт Евклидом, так как упоминание о нём имеется уже в Топике Аристотеля (IV век до н. э.)[3]. В «Началах» Евклида он описан дважды — в VII книге для нахождения наибольшего общего делителя двух натуральных чисел[1] и в X книге для нахождения наибольшей общей меры двух однородных величин[2]. В обоих случаях дано геометрическое описание алгоритма, для нахождения «общей меры» двух отрезков.
Историками математики было выдвинуто предположение, что именно с помощью алгоритма Евклида (процедуры последовательного взаимного вычитания) в древнегреческой математике впервые было открыто существование несоизмеримых величин (стороны и диагонали квадрата, или стороны и диагонали правильного пятиугольника)[10]. Впрочем, это предположение не имеет достаточных документальных подтверждений. Алгоритм для поиска наибольшего общего делителя двух натуральных чисел описан также в I книге древнекитайского трактата Математика в девяти книгах.
Описание[править | править код]
Алгоритм Евклида для целых чисел[править | править код]
Пусть и — целые числа, не равные одновременно нулю, и последовательность чисел
определена тем, что каждое — это остаток от деления предпредыдущего числа на предыдущее, а предпоследнее делится на последнее нацело, то есть:
Тогда НОД(a, b), наибольший общий делитель a и b, равен rn, последнему ненулевому члену этой последовательности[11].
Существование таких r1, r2, …, rn, то есть возможность деления с остатком m на n для любого целого m и целого n ≠ 0, доказывается индукцией по m.
Корректность этого алгоритма вытекает из следующих двух утверждений[12]:
I. Пусть a = b⋅q + r, тогда НОД (a, b) = НОД (b, r).
Доказательство
- Пусть k — любой общий делитель чисел a и b, не обязательно наибольший, тогда a = t1⋅k и b = t2⋅k, где t1 и t2 — целые числа из определения.
- Тогда k является также общим делителем чисел b и r, так как b делится на k по определению, а (выражение в скобках есть целое число, следовательно, k делит r без остатка).
- Обратное также верно и доказывается аналогично пункту 2: любой делитель b и r так же является делителем a и b.
- Следовательно, все общие делители пар чисел (a, b) и (b, r) совпадают. Другими словами, нет общего делителя у чисел (a, b), который не был бы также делителем (b, r), и наоборот.
- В частности, наибольший общий делитель остаётся тем же самым, так как в предположении, что НОД (a, b) > НОД (b, r) или НОД (a, b) < НОД (b, r) получаются противоречия, следовательно, НОД (a, b) = НОД (b, r). Что и требовалось доказать.
II. НОД(r, 0) = r для любого ненулевого r (так как 0 делится на любое целое число).
Геометрический алгоритм Евклида[править | править код]
Пусть даны два отрезка длины a и b. Вычтем из большего отрезка меньший и заменим больший отрезок полученной разностью. Повторяем эту операцию, вычитая из большего отрезка меньший, пока отрезки не станут равны. Если это произойдёт, то исходные отрезки соизмеримы, и последний полученный отрезок есть их наибольшая общая мера. Если общей меры нет, то процесс бесконечен. В таком виде алгоритм описан Евклидом[2] и реализуется с помощью циркуля и линейки.
Пример[править | править код]
Для иллюстрации алгоритм Евклида будет использован, чтобы найти НОД a = 1071 и b = 462. Для начала от 1071 отнимем кратное значение 462, пока не получим разность меньше, чем 462. Мы должны дважды отнять 462, (q0 = 2), оставаясь с остатком 147:
- 1071 = 2 × 462 + 147.
Затем от 462 отнимем кратное значение 147, пока не получим разность меньше, чем 147. Мы должны трижды отнять 147 (q1 = 3), оставаясь с остатком 21:
- 462 = 3 × 147 + 21.
Затем от 147 отнимем кратное значение 21, пока не получим разность меньше, чем 21. Мы должны семь раз отнять 21 (q2 = 7), оставаясь без остатка:
- 147 = 7 × 21 + 0.
Таким образом последовательность a > b > r1 > r2 > r3 > … > rn в данном конкретном случае будет выглядеть так:
- 1071 > 462 > 147 > 21.
Так как последний остаток равен нулю, алгоритм заканчивается числом 21 и НОД(1071, 462) = 21.
В табличной форме шаги были следующие:
Шаг k | Равенство | Частное и остаток |
---|---|---|
0 | 1071 = q0 462 + r0 | q0 = 2 и r0 = 147 |
1 | 462 = q1 147 + r1 | q1 = 3 и r1 = 21 |
2 | 147 = q2 21 + r2 | q2 = 7 и r2 = 0; алгоритм заканчивается |
Если требуется найти НОД для более чем двух чисел, алгоритм аналогичен, на каждом шаге все числа, кроме
наименьшего, заменяются остатками по модулю наименьшего. Нулевые остатки, если получатся, вычёркиваются. Алгоритм завершается, когда остаётся одно ненулевое число, это и есть НОД.
Применения[править | править код]
Расширенный алгоритм Евклида и соотношение Безу[править | править код]
Формулы для могут быть переписаны следующим образом:
- НОД
Здесь s и t целые. Это представление наибольшего общего делителя называется соотношением Безу, а числа s и t — коэффициентами Безу[13]. Соотношение Безу является ключевым в доказательстве леммы Евклида и основной теоремы арифметики.
Цепные дроби[править | править код]
Алгоритм Евклида достаточно тесно связан с цепными дробями[6]. Отношение a/b допускает представление в виде цепной дроби:
-
- .
При этом цепная дробь без последнего члена равна отношению коэффициентов Безу t/s, взятому со знаком минус:
-
- .
Последовательность равенств, задающая алгоритм Евклида, может быть переписана в форме:
Последнее слагаемое в правой части равенства всегда равно обратному значению левой части следующего уравнения. Поэтому первые два уравнения могут быть объединены в форме:
Третье равенство может быть использовано, чтобы заменить знаменатель выражения r1/r0, получим:
Последнее отношение остатков rk/rk−1 всегда может быть заменено с использованием следующего равенства в последовательности, и так до последнего уравнения. Результатом является цепная дробь:
В приведённом выше примере НОД(1071, 462) был посчитан и были найдены частные qk, равные 2, 3 и 7 соответственно. Поэтому 1071/462 может быть записана как:
Линейные диофантовы уравнения[править | править код]
Диофантово уравнение — это уравнение с целочисленными коэффициентами и с одним или несколькими переменными, причём ставится задача поиска лишь его целых корней. Такое уравнение может иметь бесконечно много решений, конечное число решений или не иметь их вовсе. Простейшее диофантово уравнение — линейное с двумя неизвестными:
где a, b, c — целые числа. С помощью алгоритма Евклида может быть найдено полное решение уравнения такого типа[5]. Сначала с помощью этого алгоритма можно определить d = НОД(a, b). Затем, используя расширенный алгоритм Евклида, определяются такие k и l, что:
То есть x = k и y = l — это частное решение уравнения при c = d. Получается, что если c = q⋅d, то x = q⋅k, y = q⋅l — частное решение исходного уравнения, так как:
Обратно, если существует хотя бы одно решение уравнения, то c кратно d. Это следует из того, что d делит и a, и b (а значит, и всю левую часть), поэтому должно делить и c (правую часть). Таким образом, линейное диофантово уравнение имеет хотя бы одно решение тогда и только тогда, когда c кратно НОД(a, b).
Вариации и обобщения[править | править код]
Евклидово кольцо[править | править код]
Кольца, в которых применим алгоритм Евклида, называются евклидовыми кольцами[14]. К ним относятся, в частности, кольца целых чисел и кольца многочленов.
Обобщённый алгоритм Евклида для многочленов[править | править код]
Алгоритм Евклида и расширенный алгоритм Евклида естественным образом обобщается на кольцо многочленов k[x] от одной переменной над произвольным полем k, поскольку для таких многочленов определена операция деления с остатком. При выполнении алгоритма Евклида для многочленов аналогично алгоритму Евклида для целых чисел получается последовательность полиномиальных остатков (PRS)[15].
Пример для кольца Z[x]
Пусть cont(f) по определению — НОД коэффициентов многочлена из — содержание многочлена. Частное от деления f(x) на cont(f) называется примитивной частью многочлена f(x) и обозначается primpart(f(x)). Эти определения понадобятся для нахождения НОД двух многочленов p1(x) и p2(x) в кольце . Для многочленов над целыми числами верно следующее:
НОДНОД
НОДНОД
Таким образом, задача поиска НОД двух произвольных многочленов сводится к задаче поиска НОД примитивных полиномов.
Пусть есть два примитивных многочлена p1(x) и p2(x) из Z[x], для которых выполняется соотношение между их степенями: deg(p1(x)) = m и deg(p2(x)) = n, m > n. Деление многочленов с остатком предполагает точную делимость старшего коэффициента делимого на старший коэффициент делителя, в общем случае деление с остатком выполнить невозможно. Поэтому вводят алгоритм псевдоделения, который всё же позволяет получить псевдочастное и псевдоостаток (prem), которые будут сами по себе принадлежать множеству многочленов над целыми числами.
Под псевдоделением будем понимать, что самому делению предшествует умножение полинома на , то есть
где и — соответственно псевдочастное и псевдоостаток.
Итак, , причём . Тогда алгоритм Евклида состоит из следующих шагов:
1. Вычисление НОД содержаний:
НОД.
2. Вычисление примитивных частей:
3. Построение последовательности полиномиальных остатков:
4. Возврат результата:
Если , то вернуть , иначе вернуть .
Ускоренные версии алгоритма[править | править код]
- Одним из методов ускорения целочисленного алгоритма Евклида является использование симметричного остатка[16]:
-
- где
- Одна из версий ускоренного алгоритма Евклида для полиномов основывается на том, что промежуточные значения алгоритма в основном зависят от высоких степеней. Применение стратегии «разделяй и властвуй» позволяет уменьшить асимптотическую сложность алгоритма[16].
Вычислительная сложность алгоритма[править | править код]
Число шагов в алгоритме Евклида для НОД(x,y). Более светлые точки (красные и жёлтые) указывают на относительно меньшее количество шагов, тогда как более тёмные точки (фиолетовые и синие) на большее количество шагов. Самая большая тёмная область следует за прямой y = Φx, где Φ — золотое сечение.
Вычислительная сложность алгоритма Евклида изучена полностью.[17] Эта сложность может быть описана произведением количества шагов деления, требуемых алгоритмом, на вычислительную сложность одного шага. Первый известный анализ алгоритма Евклида был предложен Рейнаудом в 1811.[18] Он показал, что число шагов алгоритма для пары чисел (u, v) ограничено v. Позже он улучшил оценку до v/2 + 2. Эмиль Леже в 1837 году изучил наихудший случай, когда для вычисления НОД подаются последовательные числа Фибоначчи.[19] Затем, в 1841 году, Пьер Джосеф Финк показал,[20] что количество шагов алгоритма не превышает 2 log2 v + 1. Следовательно, алгоритм работает за полиномиальное время от размера меньшего из пары чисел (u, v).[19] Анализ Финка был уточнён Габриэлем Ламе в 1844 году.[21] Он показал, что количество шагов, необходимых для завершения алгоритма, не более чем в пять раз превышает h — количество цифр в десятичном представлении меньшего из пары чисел (u, v).[22][23]
Когда НОД вычисляется для чисел, которые вписываются в одно машинное слово, каждый шаг алгоритма занимает постоянное время. В данном случае анализ Ламе предполагает, что вычислительная сложность оценивается как O(h). Однако в модели расчёта, подходящей для вычислений с числами больше одного машинного слова, оценка сложности вычисления одного остатка может быть O(h2).[24] В этом случае общее время для всех этапов алгоритма можно проанализировать с помощью телескопического ряда, показав, что это также O(h2). Для ускорения алгоритма Евклида могут быть использованы современные алгоритмические методы, основанные на методе Шёнхаге — Штрассена для быстрого целочисленного умножения. Это приводит к квазиполиномиальному времени.[25]
Количество шагов[править | править код]
Число шагов для вычисления НОД двух натуральных чисел a и b обозначим как T(a, b). Если g — это наибольший общий делитель a и b, тогда a = mg и b = ng для двух взаимно простых чисел m и n. Тогда T(a, b) = T(m, n), что можно заметить, если разделить уравнения, полученные при вычислении НОД для пары (a, b), на g.[26] Используя тот же принцип, число шагов алгоритма остаётся неизменным, если a и b умножаются на общий множитель w, что эквивалентно равенству T(a, b) = T(wa, wb). Следовательно, количество шагов T может сильно различаться между соседними парами чисел, такими как (a, b) и (a, b+1), так как данная величина зависит от НОД.
Рекурсивный характер алгоритма Евклида даёт следующее уравнение T(a, b) = 1 + T(b, r0) = 2 + T(r0, r1) = … = N + T(rN−2, rN−1) = N + 1, где T(x, 0) = 0 по предположению.[17]
Наихудший случай[править | править код]
Если для алгоритма Евклида требуются N шагов для пары натуральных чисел a > b > 0, наименьшие значения a и b, для которых это выполняется — числа Фибоначчи FN+2 и FN+1 соответственно.[27] Тогда, если алгоритм Евклида требует N шагов для пары чисел (a,b), где a > b, выполняются следующие неравенства a ≥ FN+2 и b ≥ FN+1. Доказать это можно по математической индукции. Если N = 1, тогда a делится на b без остатка. Наименьшие натуральные числа, для которых это верно, равны b = 1 и a = 2, соответственно F2 и F3. Предположим теперь, что результат выполняется для всех значений N до M − 1. Первый шаг алгоритма Евклида с M шагами a = q0b + r0, и алгоритм Евклида для пары чисел (b,r0), где b > r0, требует M − 1 шагов. По предположению индукции имеем b ≥ FM+1 и r0 ≥ FM. Следовательно, a = q0b + r0 ≥ b + r0 ≥ FM+1 + FM = FM+2, что является искомым неравенством. Это доказательство, опубликованное Габриэлем Ламе в 1844 году, представляет собой начало теории сложности вычислений,[28] а также первое практическое применение чисел Фибоначчи.[27]
Теорема Ламе[править | править код]
Число делений с остатком в процессе применения алгоритма Евклида не превосходит упятеренного количества цифр меньшего числа , записанного в десятичной системе[29].
Среднее[править | править код]
Существуют различные способы вычисления среднего количества шагов алгоритма. Первый способ вычисления — среднее время T(a), необходимое для вычисления НОД заданного числа a и меньшего натурального числа b, выбранного с равной вероятностью из целых чисел от 0 до a − 1.[17]
Однако, поскольку T(a, b) сильно колеблется в зависимости от НОД двух чисел, усреднённая функция T(a) также является «шумной».[30] Для того, чтобы уменьшить этот шум, второе среднее τ(a) берётся по всем числам, взаимно простым с a.
где φ(a) функция Эйлера. Это среднее плавно растёт с ростом a.[31]
Константа (константа Портера[32]) в этой формуле , а ε является бесконечно малым.
Третье среднее значение Y(n) определяется как среднее число шагов, требуемых, когда a и b выбираются случайным образом (с равномерным распределением) от 1 до n.
Вычислительная сложность шага[править | править код]
На каждом шаге алгоритма Евклида вычисляется коэффициент qk и остаток rk для заданной пары целых чисел rk−2 и rk−1. Эти величины связаны следующим соотношением:
- rk−2 = qk rk−1 + rk
Вычислительная сложность каждого шага связана главным образом с нахождением qk, так как остаток rk можно быстро вычислить, используя rk−2, rk−1, и qk
- rk = rk−2 − qk rk−1
Вычислительная сложность операции деления чисел размером h бит оценивается как O(h(ℓ+1)), где ℓ размер частного.[24]
Для сравнения, исходный алгоритм Евклида, с использованием вычитания, может быть намного медленнее. В большинстве случаев коэффициент qk является малым числом. Вероятность данного частного q примерно равна ln|u/(u − 1)|, где u = (q + 1)2.[33] Для иллюстрации вероятность частного 1, 2, 3 или 4 составляет примерно 41,5 %, 17,0 %, 9,3 % и 5,9 % соответственно. Так как операция вычитания быстрее, чем деление, особенно для чисел больше одного машинного слова,[34] алгоритм Евклида с использованием вычитания может быть более конкурентоспособным в сравнении с алгоритмом, использующим деление.[35] Это используется в бинарном алгоритме вычисления НОД.[36]
Оценка сложности алгоритма вычисляется как произведение количества шагов на время выполнения одного шага. Она показывает, что алгоритм Евклида растёт квадратично O(h2), где h — среднее число цифр в двух начальных числах a и b в десятичной записи. Пусть h0, h1, …, hN−1 представляют число цифр в последовательных остатках r0, r1, …, rN−1. Так как число шагов N растёт линейно с h, время работы ограничено следующим выражением:
Примечания[править | править код]
- ↑ 1 2 Мордухай-Болтовской, 1949, с. 11—13.
- ↑ 1 2 3 Мордухай-Болтовской, 1949, с. 103—105.
- ↑ 1 2 Кнут, 2001, с. 378.
- ↑ Menezes, 1996, с. 286.
- ↑ 1 2 Курант, 2001, с. 74—76.
- ↑ 1 2 Виноградов, 1952, с. 14—18.
- ↑ Энгелер, 1987, с. 24—31.
- ↑ Тихомиров, 2003, с. 11—14.
- ↑ Калужин, 1969, с. 6—14.
- ↑ Цейтен, 1932, с. 112—114.
- ↑ Виноградов, 1952, с. 9—10.
- ↑ Курант, 2001, с. 67—70.
- ↑ Хассе, 1953, с. 29—30.
- ↑ Курош, 1973, с. 91—92.
- ↑ Панкратьев, 2007, с. 54—58.
- ↑ 1 2 Gathen, 2013, с. 313—326.
- ↑ 1 2 3 Knuth, 1997, с. 344.
- ↑ Shallit, 1994, с. 414.
- ↑ 1 2 Shallit, 1994, с. 401—419.
- ↑ Shallit, 1994, с. 413.
- ↑ Lame, 1844, с. 867—870.
- ↑ Grossman, 1924, с. 443.
- ↑ Абрамов С. А. Математические построения и программирование. — М., Наука, 1978. — Тираж 100 000 экз. — c. 170
- ↑ 1 2 Knuth, 1997, с. 257—261.
- ↑ Moeller, 2005, с. 1.
- ↑ Ore, 1948, с. 45.
- ↑ 1 2 Knuth, 1997, с. 343.
- ↑ LeVeque, 1996, с. 3.
- ↑ Абрамов С. А. Математические построения и программирование. — М., Наука, 1978. — Тираж 100 000 экз. — c. 170
- ↑ Knuth, 1997, с. 353.
- ↑ Tonkov, 1974, с. 47—57.
- ↑ Weisstein, Eric W. Porter’s Constant (англ.) на сайте Wolfram MathWorld.
- ↑ Knuth, 1997, с. 352.
- ↑ Wagon, 1999, с. 335—336.
- ↑ Cohen, 1993, с. 14.
- ↑ Cohen, 1993, с. 14—15, 17-18.
Литература[править | править код]
- Абрамов С. А. Самый знаменитый алгоритм // Квант / под ред. И. К. Кикоин, Ю. А. Осипьян, В. В. Козлов, А. Л. Семёнов, А. А. Гайфуллин — МИАН, 1985. — вып. 11. — С. 44—46. — ISSN 0130-2221
- Виноградов И. М. Основы теории чисел. — М.—Л.: ГИТТЛ, 1952. — 180 с. — ISBN 978-5-811-40535-0.
- Калужин Л. А. Основная теорема арифметики. — Популярные лекции по математике. — М.: Наука, 1969. — 33 с.
- Кнут Д. Э. Искусство программирования. — Вильямс, 2001. — Т. 2. — 829 с. — ISBN 5-8459-0081-6.
- Курант Р., Роббинс Г. Дополнение к главе I, § 4. // Что такое математика? — 3-e изд., испр. и доп. — М., 2001. — 568 с. — ISBN 5-900916-45-6.
- Курош А. Г. Лекции по общей алгебре / под ред. О. Н. Головин — 2-е изд. — М.: Наука, 1973. — 400 с. — ISBN 978-5-8114-0617-3
- Начала Евклида / пер.с греч. и комм. Д. Д. Мордухая-Болтовского под ред. Выгодского М. Я. и Веселовского И. Н.. — ГИТТЛ, 1949. — Т. 2. — 511 с.
- Панкратьев Е. В. Элементы компьютерной алгебры. — ИНТУИТ, 2007. — 217 с. — ISBN 978-5-955-60099-4.
- Тихомиров В. М. Великие математики прошлого и их великие теоремы. — 2-е изд., испр. — МЦНМО, 2003. — 16 с. — ISBN 5-94057-110-7.
- Хассе Г. Лекции по теории чисел. — Изд. иностранной литературы, 1953. — 527 с.
- Цейтен Г. Г. История математики в Древности и в Средние века. — ГТТИ, 1932. — 232 с.
- Энгелер Э. Метаматематика элементарной математики. — М.: Мир, 1987. — 128 с.
- Cohen H. A Course in Computational Algebraic Number Theory. — Springer-Verlag, 1993. — ISBN 0-387-55640-0.
- von zur Gathen J., Gerhard J. Modern Computer Algebra. — Cambridge University Press, 2013. — 808 с. — ISBN 978-1-107-03903-2.
- Grossman H. On the Number of Divisions in Finding a G.C.D. (англ.) // The American Mathematical Monthly. — 1924. — Vol. 31, iss. 9. — P. 443. — doi:10.2307/2298146. — JSTOR 2298146.
- Knuth D. E. The Art of Computer Programming. — 3. — Addison–Wesley, 1997. — Т. 2: Seminumerical Algorithms. — ISBN 0-201-89684-2.
- Lamé G. Note sur la limite du nombre des divisions dans la recherche du plus grand commun diviseur entre deux nombres entiers (фр.). — Comptes Rendus Acad. Sci., 1844. — No 19.
- LeVeque W. J. Fundamentals of Number Theory (англ.). — Dover, 1996. — ISBN 0-486-68906-9.
- Menezes A., van Oorschot P., Vanstone S. Handbook of Applied Cryptography. — CRC-Press, 1996. — 816 с. — (Discrete Mathematics and Its Applications). — ISBN 0-8493-8523-7.
- Moeller Niels. Mathematics of Computation (англ.). — 2005.
- Ore O. Number Theory and Its History (англ.). — McGraw–Hill, 1948.
- Shallit J. Origins of the analysis of the Euclidean algorithm (англ.) // Historia Math.. — 1994. — Vol. 21. — doi:10.1006/hmat.1994.1031.
- Tonkov T. On the average length of finite continued fractions (англ.) // Acta Arithmetica. — 1974. — Vol. 26.
- Wagon S. Mathematica in Action (англ.). — Springer-Verlag, 1999. — ISBN 0-387-98252-3.
Ссылки[править | править код]
- Реализация алгоритма Евклида на языке Pascal
- Алгоритм Евклида на e-maxx.ru
- Реализация расширенного алгоритма Евклида на языке C
Рассмотрим два основных метода нахождения НОД двумя основными способами: с использованием алгоритма Евклида и путем разложения на простые множители. Применим оба метода для двух, трех и большего количества чисел.
Алгоритм Евклида для нахождения НОД
Алгоритм Евклида позволяет с легкостью вычислить наибольший общий делитель для двух положительных чисел. Формулировки и доказательство алгоритма Евклида мы привели в разделе «Наибольший общий делитель: определитель, примеры».
Суть алгоритма заключается в том, чтобы последовательно проводить деление с остатком, в ходе которого получается ряд равенств вида:
a=b·q1+r1, 0<r1<bb=r1·q2+r2, 0<r2<r1r1=r2·q3+r3, 0<r3<r2r2=r3·q4+r4, 0<r4<r3⋮rk-2=rk-1·qk+rk, 0<rk<rk-1rk-1=rk·qk+1
Мы можем закончить деление тогда, когда rk+1=0, при этом rk=НОД(a, b).
Найдите наибольший общий делитель чисел 64 и 48.
Решение
Введем обозначения: a=64, b=48.
На основе алгоритма Евклида проведем деление 64 на 48.
Получим 1 и остаток 16. Получается, что q1=1, r1=16.
Вторым шагом разделим 48 на 16, получим 3. То есть q2=3, а r2=0. Таким образом число 16 – это наибольший общий делитель для чисел из условия.
Ответ: НОД(64, 48)=16.
Чему равен НОД чисел 111 и 432?
Решение
Делим 432 на 111. Согласно алгоритму Евклида получаем цепочку равенств 432=111·3+99, 111=99·1+12, 99=12·8+3, 12=3·4.
Таким образом, наибольший общий делитель чисел 111 и 432 – это 3.
Ответ: НОД(111, 432)=3.
Найдите наибольший общий делитель чисел 661 и 113.
Решение
Проведем последовательно деление чисел и получим НОД(661, 113)=1. Это значит, что 661 и 113 – это взаимно простые числа. Мы могли выяснить это до начала вычислений, если бы обратились к таблице простых чисел.
Ответ: НОД(661, 113)=1.
Нахождение НОД с помощью разложения чисел на простые множители
Для того, чтобы найти наибольший общий делитель двух чисел методом разложения на множители, необходимо перемножить все простые множители, которые получаются при разложении этих двух чисел и являются для них общими.
Если мы разложим числа 220 и 600 на простые множители, то получим два произведения: 220=2·2·5·11 и 600=2·2·2·3·5·5. Общими в этих двух произведениях будут множители 2,2 и 5. Это значит, что НОД(220, 600)=2·2·5=20.
Найдите наибольший общий делитель чисел 72 и 96.
Решение
Найдем все простые множители чисел 72 и 96:
72361893122233
96482412631222223
Общими для двух чисел простые множители: 2, 2, 2 и 3. Это значит, что НОД(72, 96)=2·2·2·3=24.
Ответ: НОД(72, 96)=24.
Правило нахождения наибольшего общего делителя двух чисел основано на свойствах наибольшего общего делителя, согласно которому НОД(m·a1, m·b1)=m·НОД(a1, b1), где m– любое целое положительное число.
Нахождение НОД трех и большего количества чисел
Независимо от количества чисел, для которых нам нужно найти НОД, мы будем действовать по одному и тому же алгоритму, который заключается в последовательном нахождении НОД двух чисел. Основан этот алгоритм на применении следующей теоремы: НОД нескольких чисел a1, a2, …, ak равен числу dk, которое находится при последовательном вычислении НОД(a1, a2)=d2, НОД(d2, a3)=d3, НОД(d3, a4)=d4, …, НОД(dk-1, ak)=dk.
Найдите наибольший общий делитель четырех чисел 78, 294, 570 и 36.
Решение
Введем обозначения: a1=78, a2=294, a3=570, a4=36.
Начнем с того, что найдем НОД чисел 78 и 294: d2=НОД(78, 294)=6.
Теперь приступим к нахождению d3=НОД(d2, a3)=НОД(6, 570). Согласно алгоритму Евклида 570=6·95. Это значит, что d3=НОД(6, 570)=6.
Найдем d4=НОД(d3, a4)=НОД(6, 36). 36 делится на 6 без остатка. Это позволяет нам получить d4=НОД(6, 36)=6.
d4=6, то есть, НОД(78, 294, 570, 36)=6.
Ответ: НОД(78, 294, 570, 36)=6.
А теперь давайте рассмотрим еще один способ вычисления НОД для тех и большего количества чисел. Мы можем найти НОД, перемножив все общие простые множители чисел.
Вычислите НОД чисел 78, 294, 570 и 36.
Решение
Произведем разложение данных чисел на простые множители: 78=2·3·13, 294=2·3·7·7, 570=2·3·5·19, 36=2·2·3·3.
Для всех четырех чисел общими простыми множителями будут числа 2 и 3.
Получается, что НОД(78, 294, 570, 36)=2·3=6.
Ответ: НОД(78, 294, 570, 36)=6.
Нахождение НОД отрицательных чисел
Если нам приходится иметь дело с отрицательными числами, то для нахождения наибольшего общего делителя мы можем воспользоваться модулями этих чисел. Мы можем так поступить, зная свойство чисел с противоположными знаками: числа n и -n имеют одинаковые делители.
Найдите НОД отрицательных целых чисел −231 и −140.
Решение
Для выполнения вычислений возьмем модули чисел, данных в условии. Это будут числа 231 и 140. Запишем это кратко: НОД(−231, −140)=НОД(231, 140). Теперь применим алгоритм Евклида для нахождения простых множителей двух чисел: 231=140·1+91; 140=91·1+49; 91=49·1+42; 49=42·1+7 и 42=7·6. Получаем, что НОД(231, 140)=7.
А так как НОД(−231, −140)=НОД(231, 140), то НОД чисел −231 и −140 равен 7.
Ответ: НОД(−231, −140)=7.
Определите НОД трех чисел −585, 81 и −189.
Решение
Заменим отрицательные числа в приведенном перечне на их абсолютные величины, получим НОД(−585, 81, −189)=НОД(585, 81, 189). Затем разложим все данные числа на простые множители: 585=3·3·5·13, 81=3·3·3·3 и 189=3·3·3·7. Общими для трех чисел являются простые множители 3 и 3. Получается , что НОД(585, 81, 189)=НОД(−585, 81, −189)=9.
Ответ: НОД(−585, 81, −189)=9.
Преподаватель математики и информатики. Кафедра бизнес-информатики Российского университета транспорта
Алгоритм Евклида
Для начала разберемся, что это и как это работает. Алгоритм Евклида позволяет найти нам наибольший общий делитель чисел. Как это работает:
Пусть a = 18, b = 30.
Цикл: a!=0 and b!=0
Если a > b, то a = a % b, если меньше, то b = b % a, таким образом мы сначала находим остаток деления, а потом повторяем действия. У нас a < b, значит, ищем остаток деления b % a (30 % 18) = 12, присваиваем b = 12, повторяем цикл но теперь у нас уже a > b(b = 12)
значит выполняем a % b (18 % 12) = 6? снова переходим к циклу, теперь снова b > a, значит выполняем b % a (30 % 6), остаток от деления 0, на этом мы прекращаем наш цикл и узнаем, что наибольший общий делитель 18 и 30 = 6. и выводим a + b (b = 0, a = 6).
Python
#!/usr/bin/env python
a = 18
b = 30
while a!=0 and b!=0:
if a > b:
a = a % b
else:
b = b % a
print (a+b)
Perl:
sub nod
{
return $_[0] != 0 ? nod ( ( $_[1] % $_[0] ), $_[0] ) : $_[1];
}
C:
int gcd(int a, int b) {
int c;
while (b) {
c = a % b;
a = b;
b = c;
}
return abs(a);
}
Pascal:
function nod( a, b: longint): longint;
begin
while (a <> 0) and (b <> 0) do
if a >= b then
a:= a mod b
else
b:= b mod a;
nod:= a + b;
end;
Java:
public class GCD {
public static int gcd(int a,int b) {
while (b !=0) {
int tmp = a%b;
a = b;
b = tmp;
}
return a;
}
}
C#:
int gcd(int a, int b)
{
while (b != 0)
b = a % (a = b);
return a;
}
Как найти НОД двух чисел по алгоритму Евклида
Содержание:
- Что такое алгоритм Евклида
- Понятие НОД
-
Основная суть алгоритма Евклида
- Последовательность нахождения НОД при помощи деления:
- Последовательность нахождения НОД при помощи вычитания:
- Примеры решения задач с алгоритмом Евклида
Что такое алгоритм Евклида
Алгоритм Евклида — один из наиболее ранних численных алгоритмов в истории. Название было дано в честь греческого математика Евклида, который впервые дал ему описание в книгах «Начала». Изначально назывался «взаимным вычитанием», так как его принцип заключался в последовательном вычитании из большего числа меньшего, пока в результате не получится ноль. Сегодня чаще используется взятие остатка от деления вместо вычитания, но суть метода сохранилась.
Алгоритм Евклида — это алгоритм, основная функция которого заключается в поиске наибольшего общего делителя (НОД) для двух целых чисел.
Простейшим случаем применения данного алгоритма является поиск наибольшего общего делителя для пары положительных целых чисел. Евклид, автор этого метода, предполагал его использование только для натуральных чисел и геометрических величин. Но позже алгоритм был обобщен и для других групп математических объектов, что привело к появлению такого понятия, как евклидово кольцо.
Осторожно! Если преподаватель обнаружит плагиат в работе, не избежать крупных проблем (вплоть до отчисления). Если нет возможности написать самому, закажите тут.
Понятие НОД
Аббревиатура НОД расшифровывается как «наибольший общий делитель».
Наибольший общий делитель — делитель, который делит без остатка два числа, при этом сам делится без остатка на любой другой делитель исходных двух чисел. То есть это самое большое число, на которое без остатка можно разделить пару чисел, для которых подбирается НОД.
Основная суть алгоритма Евклида
Суть алгоритма заключается в построении ряда следующего вида (при условии, что a больше b):
a, b, x1, x2, x3, … xn.
В нем каждое последующее число — это остаток от деления двух предыдущих, ряд заканчивается, когда остаток от деления становится равным 0 — при условии использования деления.
В нем каждое последующее число является результатом вычитания двух предыдущих, ряд заканчивается, когда частное становится равным 0 — при условии использования вычитания.
Последовательность нахождения НОД при помощи деления:
- Большее число делится на меньшее.
- Если результат деления:
- без остатка, то меньшее число и есть НОД;
- с остатком, тогда большее число заменяется на остаток.
- Переход к пункту 1.
Пример №1
60 / 36 = 1 (остаток 24)
36 / 24 = 1 (остаток 12)
24 / 12 = 2 (остаток 0)
НОД для 60 и 36 равен 12 (делитель).
Последовательность нахождения НОД при помощи вычитания:
- Из большего числа вычитается меньшее.
- Если результат вычитания:
- равен 0, то числа равны друг другу и являются НОД;
- не равен 0, в таком случае большее число заменяется на результат вычитания.
- Переход к пункту 1.
Пример №2
60 — 36 = 24
36 — 24 = 12
24 — 12 = 12
12 — 12 = 0
НОД для 60 и 36 равен 12 (уменьшаемое, вычитаемое)
Примеры решения задач с алгоритмом Евклида
Задача №1
Найти наибольший общий делитель для чисел 128 и 96.
Решение:
128 — 96 = 32
96 — 32 = 64
64 — 32 = 32
32 — 32 = 0
Или
128 / 96 = 1 (остаток 32)
96 / 32 = 3
Ответ: 32
Задача №2
Найти наибольший общий делитель для чисел 37 и 17.
Решение:
37 / 17 = 2 (остаток 3)
17 / 3 = 5 (остаток 2)
3 / 2 = 1 (остаток 1)
2 / 1 = 2 (остаток 0)
Или
37 — 17= 20
20 — 17 = 3
17 — 3 = 14
14 — 3 = 11
11 — 3 = 8
8 — 3 = 5
5 — 3 = 2
3 — 2 = 1
2 — 1 = 1
1 — 1 = 0
Числа 37 и 17 являются простыми, соответственно, их НОД — единица. Совет: перед вычислениями проверяйте таблицу простых чисел.
Ответ: 1
Насколько полезной была для вас статья?
Рейтинг: 4.50 (Голосов: 18)
Выделите текст и нажмите одновременно клавиши «Ctrl» и «Enter»
Текст с ошибкой:
Расскажите, что не так
Поиск по содержимому
This article is about an algorithm for the greatest common divisor. For the mathematics of space, see Euclidean geometry. For other uses of “Euclidean”, see Euclidean (disambiguation).
Euclid’s method for finding the greatest common divisor (GCD) of two starting lengths BA and DC, both defined to be multiples of a common “unit” length. The length DC being shorter, it is used to “measure” BA, but only once because the remainder EA is less than DC. EA now measures (twice) the shorter length DC, with remainder FC shorter than EA. Then FC measures (three times) length EA. Because there is no remainder, the process ends with FC being the GCD. On the right Nicomachus’s example with numbers 49 and 21 resulting in their GCD of 7 (derived from Heath 1908:300).
In mathematics, the Euclidean algorithm,[note 1] or Euclid’s algorithm, is an efficient method for computing the greatest common divisor (GCD) of two integers (numbers), the largest number that divides them both without a remainder. It is named after the ancient Greek mathematician Euclid, who first described it in his Elements (c. 300 BC).
It is an example of an algorithm, a step-by-step procedure for performing a calculation according to well-defined rules,
and is one of the oldest algorithms in common use. It can be used to reduce fractions to their simplest form, and is a part of many other number-theoretic and cryptographic calculations.
The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. For example, 21 is the GCD of 252 and 105 (as 252 = 21 × 12 and 105 = 21 × 5), and the same number 21 is also the GCD of 105 and 252 − 105 = 147. Since this replacement reduces the larger of the two numbers, repeating this process gives successively smaller pairs of numbers until the two numbers become equal. When that occurs, they are the GCD of the original two numbers. By reversing the steps or using the extended Euclidean algorithm, the GCD can be expressed as a linear combination of the two original numbers, that is the sum of the two numbers, each multiplied by an integer (for example, 21 = 5 × 105 + (−2) × 252). The fact that the GCD can always be expressed in this way is known as Bézout’s identity.
The version of the Euclidean algorithm described above (and by Euclid) can take many subtraction steps to find the GCD when one of the given numbers is much bigger than the other. A more efficient version of the algorithm shortcuts these steps, instead replacing the larger of the two numbers by its remainder when divided by the smaller of the two (with this version, the algorithm stops when reaching a zero remainder). With this improvement, the algorithm never requires more steps than five times the number of digits (base 10) of the smaller integer. This was proven by Gabriel Lamé in 1844 (Lamé’s Theorem),[1][2] and marks the beginning of computational complexity theory. Additional methods for improving the algorithm’s efficiency were developed in the 20th century.
The Euclidean algorithm has many theoretical and practical applications. It is used for reducing fractions to their simplest form and for performing division in modular arithmetic. Computations using this algorithm form part of the cryptographic protocols that are used to secure internet communications, and in methods for breaking these cryptosystems by factoring large composite numbers. The Euclidean algorithm may be used to solve Diophantine equations, such as finding numbers that satisfy multiple congruences according to the Chinese remainder theorem, to construct continued fractions, and to find accurate rational approximations to real numbers. Finally, it can be used as a basic tool for proving theorems in number theory such as Lagrange’s four-square theorem and the uniqueness of prime factorizations.
The original algorithm was described only for natural numbers and geometric lengths (real numbers), but the algorithm was generalized in the 19th century to other types of numbers, such as Gaussian integers and polynomials of one variable. This led to modern abstract algebraic notions such as Euclidean domains.
Background: greatest common divisor[edit]
The Euclidean algorithm calculates the greatest common divisor (GCD) of two natural numbers a and b. The greatest common divisor g is the largest natural number that divides both a and b without leaving a remainder. Synonyms for GCD include greatest common factor (GCF), highest common factor (HCF), highest common divisor (HCD), and greatest common measure (GCM). The greatest common divisor is often written as gcd(a, b) or, more simply, as (a, b),[3] although the latter notation is ambiguous, also used for concepts such as an ideal in the ring of integers, which is closely related to GCD.
If gcd(a, b) = 1, then a and b are said to be coprime (or relatively prime).[4] This property does not imply that a or b are themselves prime numbers.[5] For example, 6 and 35 factor as 6 = 2 × 3 and 35 = 5 × 7, so they are not prime, but their prime factors are different, so 6 and 35 are coprime, with no common factors other than 1.
A 24×60 rectangle is covered with ten 12×12 square tiles, where 12 is the GCD of 24 and 60. More generally, an a×b rectangle can be covered with square tiles of side-length c only if c is a common divisor of a and b.
Let g = gcd(a, b). Since a and b are both multiples of g, they can be written a = mg and b = ng, and there is no larger number G > g for which this is true. The natural numbers m and n must be coprime, since any common factor could be factored out of m and n to make g greater. Thus, any other number c that divides both a and b must also divide g. The greatest common divisor g of a and b is the unique (positive) common divisor of a and b that is divisible by any other common divisor c.[6]
The greatest common divisor can be visualized as follows.[7] Consider a rectangular area a by b, and any common divisor c that divides both a and b exactly. The sides of the rectangle can be divided into segments of length c, which divides the rectangle into a grid of squares of side length c. The GCD g is the largest value of c for which this is possible. For illustration, a 24×60 rectangular area can be divided into a grid of: 1×1 squares, 2×2 squares, 3×3 squares, 4×4 squares, 6×6 squares or 12×12 squares. Therefore, 12 is the GCD of 24 and 60. A 24×60 rectangular area can be divided into a grid of 12×12 squares, with two squares along one edge (24/12 = 2) and five squares along the other (60/12 = 5).
The greatest common divisor of two numbers a and b is the product of the prime factors shared by the two numbers, where each prime factor can be repeated as many times as divides both a and b.[8] For example, since 1386 can be factored into 2 × 3 × 3 × 7 × 11, and 3213 can be factored into 3 × 3 × 3 × 7 × 17, the GCD of 1386 and 3213 equals 63 = 3 × 3 × 7, the product of their shared prime factors (with 3 repeated since 3 × 3 divides both). If two numbers have no common prime factors, their GCD is 1 (obtained here as an instance of the empty product), in other words they are coprime. A key advantage of the Euclidean algorithm is that it can find the GCD efficiently without having to compute the prime factors.[9][10] Factorization of large integers is believed to be a computationally very difficult problem, and the security of many widely used cryptographic protocols is based upon its infeasibility.[11]
Another definition of the GCD is helpful in advanced mathematics, particularly ring theory.[12] The greatest common divisor g of two nonzero numbers a and b is also their smallest positive integral linear combination, that is, the smallest positive number of the form ua + vb where u and v are integers. The set of all integral linear combinations of a and b is actually the same as the set of all multiples of g (mg, where m is an integer). In modern mathematical language, the ideal generated by a and b is the ideal generated by g alone (an ideal generated by a single element is called a principal ideal, and all ideals of the integers are principal ideals). Some properties of the GCD are in fact easier to see with this description, for instance the fact that any common divisor of a and b also divides the GCD (it divides both terms of ua + vb). The equivalence of this GCD definition with the other definitions is described below.
The GCD of three or more numbers equals the product of the prime factors common to all the numbers,[13] but it can also be calculated by repeatedly taking the GCDs of pairs of numbers.[14] For example,
- gcd(a, b, c) = gcd(a, gcd(b, c)) = gcd(gcd(a, b), c) = gcd(gcd(a, c), b).
Thus, Euclid’s algorithm, which computes the GCD of two integers, suffices to calculate the GCD of arbitrarily many integers.
Description[edit]
Procedure[edit]
The Euclidean algorithm proceeds in a series of steps, with the output of each step used as the input for the next. Track the steps using an integer counter k, so the initial step corresponds to k = 0, the next step to k = 1, and so on.
Each step begins with two nonnegative remainders rk−2 and rk−1, with rk−2 > rk−1. The kth step performs division-with-remainder to find the quotient qk and remainder rk so that:
That is, multiples of the smaller number rk−1 are subtracted from the larger number rk−2 until the remainder rk is smaller than rk−1. Then the algorithm proceeds to the (k+1)th step starting with rk−1 and rk.
In the initial step k = 0, the remainders are set to r−2 = a and r−1 = b, the numbers for which the GCD is sought. In the next step k = 1, the remainders are r−1 = b and the remainder r0 of the initial step, and so on. The algorithm proceeds in a sequence of equations
The algorithm need not be modified if a < b: in that case, the initial quotient is q0 = 0, the first remainder is r0 = a, and henceforth rk−2 > rk−1 for all k ≥ 1.
Since the remainders are non-negative integers that decrease with every step, the sequence cannot be infinite, so the algorithm must eventually fail to produce the next step; but the division algorithm can always proceed to the (N+1)th step provided rN > 0. Thus the algorithm must eventually produce a zero remainder rN = 0.[15] The final nonzero remainder is the greatest common divisor of a and b:
Proof of validity[edit]
The validity of the Euclidean algorithm can be proven by a two-step argument.[16] In the first step, the final nonzero remainder rN−1 is shown to divide both a and b. Since it is a common divisor, it must be less than or equal to the greatest common divisor g. In the second step, it is shown that any common divisor of a and b, including g, must divide rN−1; therefore, g must be less than or equal to rN−1. These two opposite inequalities imply rN−1 = g.
To demonstrate that rN−1 divides both a and b (the first step), rN−1 divides its predecessor rN−2
- rN−2 = qN rN−1
since the final remainder rN is zero. rN−1 also divides its next predecessor rN−3
- rN−3 = qN−1 rN−2 + rN−1
because it divides both terms on the right-hand side of the equation. Iterating the same argument, rN−1 divides all the preceding remainders, including a and b. None of the preceding remainders rN−2, rN−3, etc. divide a and b, since they leave a remainder. Since rN−1 is a common divisor of a and b, rN−1 ≤ g.
In the second step, any natural number c that divides both a and b (in other words, any common divisor of a and b) divides the remainders rk. By definition, a and b can be written as multiples of c : a = mc and b = nc, where m and n are natural numbers. Therefore, c divides the initial remainder r0, since r0 = a − q0b = mc − q0nc = (m − q0n)c. An analogous argument shows that c also divides the subsequent remainders r1, r2, etc. Therefore, the greatest common divisor g must divide rN−1, which implies that g ≤ rN−1. Since the first part of the argument showed the reverse (rN−1 ≤ g), it follows that g = rN−1. Thus, g is the greatest common divisor of all the succeeding pairs:[17][18]
- g = gcd(a, b) = gcd(b, r0) = gcd(r0, r1) = … = gcd(rN−2, rN−1) = rN−1.
Worked example[edit]
Subtraction-based animation of the Euclidean algorithm. The initial rectangle has dimensions a = 1071 and b = 462. Squares of size 462×462 are placed within it leaving a 462×147 rectangle. This rectangle is tiled with 147×147 squares until a 21×147 rectangle is left, which in turn is tiled with 21×21 squares, leaving no uncovered area. The smallest square size, 21, is the GCD of 1071 and 462.
For illustration, the Euclidean algorithm can be used to find the greatest common divisor of a = 1071 and b = 462. To begin, multiples of 462 are subtracted from 1071 until the remainder is less than 462. Two such multiples can be subtracted (q0 = 2), leaving a remainder of 147:
- 1071 = 2 × 462 + 147.
Then multiples of 147 are subtracted from 462 until the remainder is less than 147. Three multiples can be subtracted (q1 = 3), leaving a remainder of 21:
- 462 = 3 × 147 + 21.
Then multiples of 21 are subtracted from 147 until the remainder is less than 21. Seven multiples can be subtracted (q2 = 7), leaving no remainder:
- 147 = 7 × 21 + 0.
Since the last remainder is zero, the algorithm ends with 21 as the greatest common divisor of 1071 and 462. This agrees with the gcd(1071, 462) found by prime factorization above. In tabular form, the steps are:
Step k | Equation | Quotient and remainder |
---|---|---|
0 | 1071 = q0 462 + r0 | q0 = 2 and r0 = 147 |
1 | 462 = q1 147 + r1 | q1 = 3 and r1 = 21 |
2 | 147 = q2 21 + r2 | q2 = 7 and r2 = 0; algorithm ends |
Visualization[edit]
The Euclidean algorithm can be visualized in terms of the tiling analogy given above for the greatest common divisor.[19] Assume that we wish to cover an a×b rectangle with square tiles exactly, where a is the larger of the two numbers. We first attempt to tile the rectangle using b×b square tiles; however, this leaves an r0×b residual rectangle untiled, where r0 < b. We then attempt to tile the residual rectangle with r0×r0 square tiles. This leaves a second residual rectangle r1×r0, which we attempt to tile using r1×r1 square tiles, and so on. The sequence ends when there is no residual rectangle, i.e., when the square tiles cover the previous residual rectangle exactly. The length of the sides of the smallest square tile is the GCD of the dimensions of the original rectangle. For example, the smallest square tile in the adjacent figure is 21×21 (shown in red), and 21 is the GCD of 1071 and 462, the dimensions of the original rectangle (shown in green).
Euclidean division[edit]
At every step k, the Euclidean algorithm computes a quotient qk and remainder rk from two numbers rk−1 and rk−2
- rk−2 = qk rk−1 + rk
where the rk is non-negative and is strictly less than the absolute value of rk−1. The theorem which underlies the definition of the Euclidean division ensures that such a quotient and remainder always exist and are unique.[20]
In Euclid’s original version of the algorithm, the quotient and remainder are found by repeated subtraction; that is, rk−1 is subtracted from rk−2 repeatedly until the remainder rk is smaller than rk−1. After that rk and rk−1 are exchanged and the process is iterated. Euclidean division reduces all the steps between two exchanges into a single step, which is thus more efficient. Moreover, the quotients are not needed, thus one may replace Euclidean division by the modulo operation, which gives only the remainder. Thus the iteration of the Euclidean algorithm becomes simply
- rk = rk−2 mod rk−1.
Implementations[edit]
Implementations of the algorithm may be expressed in pseudocode. For example, the division-based version may be programmed as[21]
function gcd(a, b) while b ≠ 0 t := b b := a mod b a := t return a
At the beginning of the kth iteration, the variable b holds the latest remainder rk−1, whereas the variable a holds its predecessor, rk−2. The step b := a mod b is equivalent to the above recursion formula rk ≡ rk−2 mod rk−1. The temporary variable t holds the value of rk−1 while the next remainder rk is being calculated. At the end of the loop iteration, the variable b holds the remainder rk, whereas the variable a holds its predecessor, rk−1.
(If negative inputs are allowed, or if the mod function may return negative values, the last line must be changed into return max(a, −a).)
In the subtraction-based version, which was Euclid’s original version, the remainder calculation (b := a mod b
) is replaced by repeated subtraction.[22] Contrary to the division-based version, which works with arbitrary integers as input, the subtraction-based version supposes that the input consists of positive integers and stops when a = b:
function gcd(a, b) while a ≠ b if a > b a := a − b else b := b − a return a
The variables a and b alternate holding the previous remainders rk−1 and rk−2. Assume that a is larger than b at the beginning of an iteration; then a equals rk−2, since rk−2 > rk−1. During the loop iteration, a is reduced by multiples of the previous remainder b until a is smaller than b. Then a is the next remainder rk. Then b is reduced by multiples of a until it is again smaller than a, giving the next remainder rk+1, and so on.
The recursive version[23] is based on the equality of the GCDs of successive remainders and the stopping condition gcd(rN−1, 0) = rN−1.
function gcd(a, b) if b = 0 return a else return gcd(b, a mod b)
(As above, if negative inputs are allowed, or if the mod function may return negative values, the instruction “return a” must be changed into “return max(a, −a)”.)
For illustration, the gcd(1071, 462) is calculated from the equivalent gcd(462, 1071 mod 462) = gcd(462, 147). The latter GCD is calculated from the gcd(147, 462 mod 147) = gcd(147, 21), which in turn is calculated from the gcd(21, 147 mod 21) = gcd(21, 0) = 21.
Method of least absolute remainders[edit]
In another version of Euclid’s algorithm, the quotient at each step is increased by one if the resulting negative remainder is smaller in magnitude than the typical positive remainder.[24][25] Previously, the equation
- rk−2 = qk rk−1 + rk
assumed that |rk−1| > rk > 0. However, an alternative negative remainder ek can be computed:
- rk−2 = (qk + 1) rk−1 + ek
if rk−1 > 0 or
- rk−2 = (qk − 1) rk−1 + ek
if rk−1 < 0.
If rk is replaced by ek. when |ek| < |rk|, then one gets a variant of Euclidean algorithm such that
- |rk| ≤ |rk−1| / 2
at each step.
Leopold Kronecker has shown that this version requires the fewest steps of any version of Euclid’s algorithm.[24][25] More generally, it has been proven that, for every input numbers a and b, the number of steps is minimal if and only if qk is chosen in order that where is the golden ratio.[26]
Historical development[edit]
The Euclidean algorithm was probably invented before Euclid, depicted here holding a compass in a painting of about 1474.
The Euclidean algorithm is one of the oldest algorithms in common use.[27] It appears in Euclid’s Elements (c. 300 BC), specifically in Book 7 (Propositions 1–2) and Book 10 (Propositions 2–3). In Book 7, the algorithm is formulated for integers, whereas in Book 10, it is formulated for lengths of line segments. (In modern usage, one would say it was formulated there for real numbers. But lengths, areas, and volumes, represented as real numbers in modern usage, are not measured in the same units and there is no natural unit of length, area, or volume; the concept of real numbers was unknown at that time.) The latter algorithm is geometrical. The GCD of two lengths a and b corresponds to the greatest length g that measures a and b evenly; in other words, the lengths a and b are both integer multiples of the length g.
The algorithm was probably not discovered by Euclid, who compiled results from earlier mathematicians in his Elements.[28][29] The mathematician and historian B. L. van der Waerden suggests that Book VII derives from a textbook on number theory written by mathematicians in the school of Pythagoras.[30] The algorithm was probably known by Eudoxus of Cnidus (about 375 BC).[27][31] The algorithm may even pre-date Eudoxus,[32][33] judging from the use of the technical term ἀνθυφαίρεσις (anthyphairesis, reciprocal subtraction) in works by Euclid and Aristotle.[34]
Centuries later, Euclid’s algorithm was discovered independently both in India and in China,[35] primarily to solve Diophantine equations that arose in astronomy and making accurate calendars. In the late 5th century, the Indian mathematician and astronomer Aryabhata described the algorithm as the “pulverizer”,[36] perhaps because of its effectiveness in solving Diophantine equations.[37] Although a special case of the Chinese remainder theorem had already been described in the Chinese book Sunzi Suanjing,[38] the general solution was published by Qin Jiushao in his 1247 book Shushu Jiuzhang (數書九章 Mathematical Treatise in Nine Sections).[39] The Euclidean algorithm was first described numerically and popularized in Europe in the second edition of Bachet’s Problèmes plaisants et délectables (Pleasant and enjoyable problems, 1624).[36] In Europe, it was likewise used to solve Diophantine equations and in developing continued fractions. The extended Euclidean algorithm was published by the English mathematician Nicholas Saunderson,[40] who attributed it to Roger Cotes as a method for computing continued fractions efficiently.[41]
In the 19th century, the Euclidean algorithm led to the development of new number systems, such as Gaussian integers and Eisenstein integers. In 1815, Carl Gauss used the Euclidean algorithm to demonstrate unique factorization of Gaussian integers, although his work was first published in 1832.[42] Gauss mentioned the algorithm in his Disquisitiones Arithmeticae (published 1801), but only as a method for continued fractions.[35] Peter Gustav Lejeune Dirichlet seems to have been the first to describe the Euclidean algorithm as the basis for much of number theory.[43] Lejeune Dirichlet noted that many results of number theory, such as unique factorization, would hold true for any other system of numbers to which the Euclidean algorithm could be applied.[44] Lejeune Dirichlet’s lectures on number theory were edited and extended by Richard Dedekind, who used Euclid’s algorithm to study algebraic integers, a new general type of number. For example, Dedekind was the first to prove Fermat’s two-square theorem using the unique factorization of Gaussian integers.[45] Dedekind also defined the concept of a Euclidean domain, a number system in which a generalized version of the Euclidean algorithm can be defined (as described below). In the closing decades of the 19th century, the Euclidean algorithm gradually became eclipsed by Dedekind’s more general theory of ideals.[46]
“[The Euclidean algorithm] is the granddaddy of all algorithms, because it is the oldest nontrivial algorithm that has survived to the present day.” |
Donald Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 2nd edition (1981), p. 318. |
Other applications of Euclid’s algorithm were developed in the 19th century. In 1829, Charles Sturm showed that the algorithm was useful in the Sturm chain method for counting the real roots of polynomials in any given interval.[47]
The Euclidean algorithm was the first integer relation algorithm, which is a method for finding integer relations between commensurate real numbers. Several novel integer relation algorithms have been developed, such as the algorithm of Helaman Ferguson and R.W. Forcade (1979)[48] and the LLL algorithm.[49][50]
In 1969, Cole and Davie developed a two-player game based on the Euclidean algorithm, called The Game of Euclid,[51] which has an optimal strategy.[52] The players begin with two piles of a and b stones. The players take turns removing m multiples of the smaller pile from the larger. Thus, if the two piles consist of x and y stones, where x is larger than y, the next player can reduce the larger pile from x stones to x − my stones, as long as the latter is a nonnegative integer. The winner is the first player to reduce one pile to zero stones.[53][54]
Mathematical applications[edit]
Bézout’s identity[edit]
Bézout’s identity states that the greatest common divisor g of two integers a and b can be represented as a linear sum of the original two numbers a and b.[55] In other words, it is always possible to find integers s and t such that g = sa + tb.[56][57]
The integers s and t can be calculated from the quotients q0, q1, etc. by reversing the order of equations in Euclid’s algorithm.[58] Beginning with the next-to-last equation, g can be expressed in terms of the quotient qN−1 and the two preceding remainders, rN−2 and rN−3:
- g = rN−1 = rN−3 − qN−1 rN−2 .
Those two remainders can be likewise expressed in terms of their quotients and preceding remainders,
- rN−2 = rN−4 − qN−2 rN−3 and
- rN−3 = rN−5 − qN−3 rN−4 .
Substituting these formulae for rN−2 and rN−3 into the first equation yields g as a linear sum of the remainders rN−4 and rN−5. The process of substituting remainders by formulae involving their predecessors can be continued until the original numbers a and b are reached:
- r2 = r0 − q2 r1
- r1 = b − q1 r0
- r0 = a − q0 b.
After all the remainders r0, r1, etc. have been substituted, the final equation expresses g as a linear sum of a and b, so that g = sa + tb.
The Euclidean algorithm, and thus Bezout’s identity, can be generalized to the context of Euclidean domains.
Principal ideals and related problems[edit]
Bézout’s identity provides yet another definition of the greatest common divisor g of two numbers a and b.[12] Consider the set of all numbers ua + vb, where u and v are any two integers. Since a and b are both divisible by g, every number in the set is divisible by g. In other words, every number of the set is an integer multiple of g. This is true for every common divisor of a and b. However, unlike other common divisors, the greatest common divisor is a member of the set; by Bézout’s identity, choosing u = s and v = t gives g. A smaller common divisor cannot be a member of the set, since every member of the set must be divisible by g. Conversely, any multiple m of g can be obtained by choosing u = ms and v = mt, where s and t are the integers of Bézout’s identity. This may be seen by multiplying Bézout’s identity by m,
- mg = msa + mtb.
Therefore, the set of all numbers ua + vb is equivalent to the set of multiples m of g. In other words, the set of all possible sums of integer multiples of two numbers (a and b) is equivalent to the set of multiples of gcd(a, b). The GCD is said to be the generator of the ideal of a and b. This GCD definition led to the modern abstract algebraic concepts of a principal ideal (an ideal generated by a single element) and a principal ideal domain (a domain in which every ideal is a principal ideal).
Certain problems can be solved using this result.[59] For example, consider two measuring cups of volume a and b. By adding/subtracting u multiples of the first cup and v multiples of the second cup, any volume ua + vb can be measured out. These volumes are all multiples of g = gcd(a, b).
Extended Euclidean algorithm[edit]
The integers s and t of Bézout’s identity can be computed efficiently using the extended Euclidean algorithm. This extension adds two recursive equations to Euclid’s algorithm[60]
- sk = sk−2 − qksk−1
- tk = tk−2 − qktk−1
with the starting values
- s−2 = 1, t−2 = 0
- s−1 = 0, t−1 = 1.
Using this recursion, Bézout’s integers s and t are given by s = sN and t = tN, where N+1 is the step on which the algorithm terminates with rN+1 = 0.
The validity of this approach can be shown by induction. Assume that the recursion formula is correct up to step k − 1 of the algorithm; in other words, assume that
- rj = sj a + tj b
for all j less than k. The kth step of the algorithm gives the equation
- rk = rk−2 − qkrk−1.
Since the recursion formula has been assumed to be correct for rk−2 and rk−1, they may be expressed in terms of the corresponding s and t variables
- rk = (sk−2 a + tk−2 b) − qk(sk−1 a + tk−1 b).
Rearranging this equation yields the recursion formula for step k, as required
- rk = sk a + tk b = (sk−2 − qksk−1) a + (tk−2 − qktk−1) b.
Matrix method[edit]
The integers s and t can also be found using an equivalent matrix method.[61] The sequence of equations of Euclid’s algorithm
can be written as a product of 2×2 quotient matrices multiplying a two-dimensional remainder vector
Let M represent the product of all the quotient matrices
This simplifies the Euclidean algorithm to the form
To express g as a linear sum of a and b, both sides of this equation can be multiplied by the inverse of the matrix M.[61][62] The determinant of M equals (−1)N+1, since it equals the product of the determinants of the quotient matrices, each of which is negative one. Since the determinant of M is never zero, the vector of the final remainders can be solved using the inverse of M
Since the top equation gives
- g = (−1)N+1 ( m22 a − m12 b),
the two integers of Bézout’s identity are s = (−1)N+1m22 and t = (−1)Nm12. The matrix method is as efficient as the equivalent recursion, with two multiplications and two additions per step of the Euclidean algorithm.
Euclid’s lemma and unique factorization[edit]
Bézout’s identity is essential to many applications of Euclid’s algorithm, such as demonstrating the unique factorization of numbers into prime factors.[63] To illustrate this, suppose that a number L can be written as a product of two factors u and v, that is, L = uv. If another number w also divides L but is coprime with u, then w must divide v, by the following argument: If the greatest common divisor of u and w is 1, then integers s and t can be found such that
- 1 = su + tw .
by Bézout’s identity. Multiplying both sides by v gives the relation
- v = suv + twv = sL + twv .
Since w divides both terms on the right-hand side, it must also divide the left-hand side, v. This result is known as Euclid’s lemma.[64] Specifically, if a prime number divides L, then it must divide at least one factor of L. Conversely, if a number w is coprime to each of a series of numbers a1, a2, …, an, then w is also coprime to their product, a1 × a2 × … × an.[64]
Euclid’s lemma suffices to prove that every number has a unique factorization into prime numbers.[65] To see this, assume the contrary, that there are two independent factorizations of L into m and n prime factors, respectively
- L = p1p2…pm = q1q2…qn .
Since each prime p divides L by assumption, it must also divide one of the q factors; since each q is prime as well, it must be that p = q. Iteratively dividing by the p factors shows that each p has an equal counterpart q; the two prime factorizations are identical except for their order. The unique factorization of numbers into primes has many applications in mathematical proofs, as shown below.
Linear Diophantine equations[edit]
Diophantine equations are equations in which the solutions are restricted to integers; they are named after the 3rd-century Alexandrian mathematician Diophantus.[66] A typical linear Diophantine equation seeks integers x and y such that[67]
- ax + by = c
where a, b and c are given integers. This can be written as an equation for x in modular arithmetic:
- ax ≡ c mod b.
Let g be the greatest common divisor of a and b. Both terms in ax + by are divisible by g; therefore, c must also be divisible by g, or the equation has no solutions. By dividing both sides by c/g, the equation can be reduced to Bezout’s identity
- sa + tb = g
where s and t can be found by the extended Euclidean algorithm.[68] This provides one solution to the Diophantine equation, x1 = s (c/g) and y1 = t (c/g).
In general, a linear Diophantine equation has no solutions, or an infinite number of solutions.[69] To find the latter, consider two solutions, (x1, y1) and (x2, y2), where
- ax1 + by1 = c = ax2 + by2
or equivalently
- a(x1 − x2) = b(y2 − y1).
Therefore, the smallest difference between two x solutions is b/g, whereas the smallest difference between two y solutions is a/g. Thus, the solutions may be expressed as
- x = x1 − bu/g
- y = y1 + au/g.
By allowing u to vary over all possible integers, an infinite family of solutions can be generated from a single solution (x1, y1). If the solutions are required to be positive integers (x > 0, y > 0), only a finite number of solutions may be possible. This restriction on the acceptable solutions allows some systems of Diophantine equations with more unknowns than equations to have a finite number of solutions;[70] this is impossible for a system of linear equations when the solutions can be any real number (see Underdetermined system).
Multiplicative inverses and the RSA algorithm[edit]
A finite field is a set of numbers with four generalized operations. The operations are called addition, subtraction, multiplication and division and have their usual properties, such as commutativity, associativity and distributivity. An example of a finite field is the set of 13 numbers {0, 1, 2, …, 12} using modular arithmetic. In this field, the results of any mathematical operation (addition, subtraction, multiplication, or division) is reduced modulo 13; that is, multiples of 13 are added or subtracted until the result is brought within the range 0–12. For example, the result of 5 × 7 = 35 mod 13 = 9. Such finite fields can be defined for any prime p; using more sophisticated definitions, they can also be defined for any power m of a prime p m. Finite fields are often called Galois fields, and are abbreviated as GF(p) or GF(p m).
In such a field with m numbers, every nonzero element a has a unique modular multiplicative inverse, a−1 such that aa−1 = a−1a ≡ 1 mod m. This inverse can be found by solving the congruence equation ax ≡ 1 mod m,[71] or the equivalent linear Diophantine equation[72]
- ax + my = 1.
This equation can be solved by the Euclidean algorithm, as described above. Finding multiplicative inverses is an essential step in the RSA algorithm, which is widely used in electronic commerce; specifically, the equation determines the integer used to decrypt the message.[73] Although the RSA algorithm uses rings rather than fields, the Euclidean algorithm can still be used to find a multiplicative inverse where one exists. The Euclidean algorithm also has other applications in error-correcting codes; for example, it can be used as an alternative to the Berlekamp–Massey algorithm for decoding BCH and Reed–Solomon codes, which are based on Galois fields.[74]
Chinese remainder theorem[edit]
Euclid’s algorithm can also be used to solve multiple linear Diophantine equations.[75] Such equations arise in the Chinese remainder theorem, which describes a novel method to represent an integer x. Instead of representing an integer by its digits, it may be represented by its remainders xi modulo a set of N coprime numbers mi:[76]
The goal is to determine x from its N remainders xi. The solution is to combine the multiple equations into a single linear Diophantine equation with a much larger modulus M that is the product of all the individual moduli mi, and define Mi as
Thus, each Mi is the product of all the moduli except mi. The solution depends on finding N new numbers hi such that
With these numbers hi, any integer x can be reconstructed from its remainders xi by the equation
Since these numbers hi are the multiplicative inverses of the Mi, they may be found using Euclid’s algorithm as described in the previous subsection.
Stern–Brocot tree[edit]
The Euclidean algorithm can be used to arrange the set of all positive rational numbers into an infinite binary search tree, called the Stern–Brocot tree.
The number 1 (expressed as a fraction 1/1) is placed at the root of the tree, and the location of any other number a/b can be found by computing gcd(a,b) using the original form of the Euclidean algorithm, in which each step replaces the larger of the two given numbers by its difference with the smaller number (not its remainder), stopping when two equal numbers are reached. A step of the Euclidean algorithm that replaces the first of the two numbers corresponds to a step in the tree from a node to its right child, and a step that replaces the second of the two numbers corresponds to a step in the tree from a node to its left child. The sequence of steps constructed in this way does not depend on whether a/b is given in lowest terms, and forms a path from the root to a node containing the number a/b.[77] This fact can be used to prove that each positive rational number appears exactly once in this tree.
For example, 3/4 can be found by starting at the root, going to the left once, then to the right twice:
The Stern–Brocot tree, and the Stern–Brocot sequences of order i for i = 1, 2, 3, 4
The Euclidean algorithm has almost the same relationship to another binary tree on the rational numbers called the Calkin–Wilf tree. The difference is that the path is reversed: instead of producing a path from the root of the tree to a target, it produces a path from the target to the root.
Continued fractions[edit]
The Euclidean algorithm has a close relationship with continued fractions.[78] The sequence of equations can be written in the form
The last term on the right-hand side always equals the inverse of the left-hand side of the next equation. Thus, the first two equations may be combined to form
The third equation may be used to substitute the denominator term r1/r0, yielding
The final ratio of remainders rk/rk−1 can always be replaced using the next equation in the series, up to the final equation. The result is a continued fraction
In the worked example above, the gcd(1071, 462) was calculated, and the quotients qk were 2, 3 and 7, respectively. Therefore, the fraction 1071/462 may be written
as can be confirmed by calculation.
Factorization algorithms[edit]
Calculating a greatest common divisor is an essential step in several integer factorization algorithms,[79] such as Pollard’s rho algorithm,[80] Shor’s algorithm,[81] Dixon’s factorization method[82] and the Lenstra elliptic curve factorization.[83] The Euclidean algorithm may be used to find this GCD efficiently. Continued fraction factorization uses continued fractions, which are determined using Euclid’s algorithm.[84]
Algorithmic efficiency[edit]
Number of steps in the Euclidean algorithm for gcd(x,y). Lighter (red and yellow) points indicate relatively few steps, whereas darker (violet and blue) points indicate more steps. The largest dark area follows the line y = Φx, where Φ is the golden ratio.
The computational efficiency of Euclid’s algorithm has been studied thoroughly.[85] This efficiency can be described by the number of division steps the algorithm requires, multiplied by the computational expense of each step. The first known analysis of Euclid’s algorithm is due to A. A. L. Reynaud in 1811,[86] who showed that the number of division steps on input (u, v) is bounded by v; later he improved this to v/2 + 2. Later, in 1841, P. J. E. Finck showed[87] that the number of division steps is at most 2 log2 v + 1, and hence Euclid’s algorithm runs in time polynomial in the size of the input.[88] Émile Léger, in 1837, studied the worst case, which is when the inputs are consecutive Fibonacci numbers.[88] Finck’s analysis was refined by Gabriel Lamé in 1844,[89] who showed that the number of steps required for completion is never more than five times the number h of base-10 digits of the smaller number b.[90][91]
In the uniform cost model (suitable for analyzing the complexity of gcd calculation on numbers that fit into a single machine word), each step of the algorithm takes constant time, and Lamé’s analysis implies that the total running time is also O(h). However, in a model of computation suitable for computation with larger numbers, the computational expense of a single remainder computation in the algorithm can be as large as O(h2).[92] In this case the total time for all of the steps of the algorithm can be analyzed using a telescoping series, showing that it is also O(h2). Modern algorithmic techniques based on the Schönhage–Strassen algorithm for fast integer multiplication can be used to speed this up, leading to quasilinear algorithms for the GCD.[93][94]
Number of steps[edit]
The number of steps to calculate the GCD of two natural numbers, a and b, may be denoted by T(a, b).[95] If g is the GCD of a and b, then a = mg and b = ng for two coprime numbers m and n. Then
- T(a, b) = T(m, n)
as may be seen by dividing all the steps in the Euclidean algorithm by g.[96] By the same argument, the number of steps remains the same if a and b are multiplied by a common factor w: T(a, b) = T(wa, wb). Therefore, the number of steps T may vary dramatically between neighboring pairs of numbers, such as T(a, b) and T(a, b + 1), depending on the size of the two GCDs.
The recursive nature of the Euclidean algorithm gives another equation
- T(a, b) = 1 + T(b, r0) = 2 + T(r0, r1) = … = N + T(rN−2, rN−1) = N + 1
where T(x, 0) = 0 by assumption.[95]
Worst-case[edit]
If the Euclidean algorithm requires N steps for a pair of natural numbers a > b > 0, the smallest values of a and b for which this is true are the Fibonacci numbers FN+2 and FN+1, respectively.[97] More precisely, if the Euclidean algorithm requires N steps for the pair a > b, then one has a ≥ FN+2 and b ≥ FN+1. This can be shown by induction.[98] If N = 1, b divides a with no remainder; the smallest natural numbers for which this is true is b = 1 and a = 2, which are F2 and F3, respectively. Now assume that the result holds for all values of N up to M − 1. The first step of the M-step algorithm is a = q0b + r0, and the Euclidean algorithm requires M − 1 steps for the pair b > r0. By induction hypothesis, one has b ≥ FM+1 and r0 ≥ FM. Therefore, a = q0b + r0 ≥ b + r0 ≥ FM+1 + FM = FM+2,
which is the desired inequality.
This proof, published by Gabriel Lamé in 1844, represents the beginning of computational complexity theory,[99] and also the first practical application of the Fibonacci numbers.[97]
This result suffices to show that the number of steps in Euclid’s algorithm can never be more than five times the number of its digits (base 10).[100] For if the algorithm requires N steps, then b is greater than or equal to FN+1 which in turn is greater than or equal to φN−1, where φ is the golden ratio. Since b ≥ φN−1, then N − 1 ≤ logφb. Since log10φ > 1/5, (N − 1)/5 < log10φ logφb = log10b. Thus, N ≤ 5 log10b. Thus, the Euclidean algorithm always needs less than O(h) divisions, where h is the number of digits in the smaller number b.
Average[edit]
The average number of steps taken by the Euclidean algorithm has been defined in three different ways. The first definition is the average time T(a) required to calculate the GCD of a given number a and a smaller natural number b chosen with equal probability from the integers 0 to a − 1[95]
However, since T(a, b) fluctuates dramatically with the GCD of the two numbers, the averaged function T(a) is likewise “noisy”.[101]
To reduce this noise, a second average τ(a) is taken over all numbers coprime with a
There are φ(a) coprime integers less than a, where φ is Euler’s totient function. This tau average grows smoothly with a[102][103]
with the residual error being of order a−(1/6) + ε, where ε is infinitesimal. The constant C in this formula is called Porter’s constant[104] and equals
where γ is the Euler–Mascheroni constant and ζ’ is the derivative of the Riemann zeta function.[105][106] The leading coefficient (12/π2) ln 2 was determined by two independent methods.[107][108]
Since the first average can be calculated from the tau average by summing over the divisors d of a[109]
it can be approximated by the formula[110]
where Λ(d) is the Mangoldt function.[111]
A third average Y(n) is defined as the mean number of steps required when both a and b are chosen randomly (with uniform distribution) from 1 to n[110]
Substituting the approximate formula for T(a) into this equation yields an estimate for Y(n)[112]
Computational expense per step[edit]
In each step k of the Euclidean algorithm, the quotient qk and remainder rk are computed for a given pair of integers rk−2 and rk−1
- rk−2 = qk rk−1 + rk.
The computational expense per step is associated chiefly with finding qk, since the remainder rk can be calculated quickly from rk−2, rk−1, and qk
- rk = rk−2 − qk rk−1.
The computational expense of dividing h-bit numbers scales as O(h(ℓ+1)), where ℓ is the length of the quotient.[92]
For comparison, Euclid’s original subtraction-based algorithm can be much slower. A single integer division is equivalent to the quotient q number of subtractions. If the ratio of a and b is very large, the quotient is large and many subtractions will be required. On the other hand, it has been shown that the quotients are very likely to be small integers. The probability of a given quotient q is approximately ln |u/(u − 1)| where u = (q + 1)2.[113] For illustration, the probability of a quotient of 1, 2, 3, or 4 is roughly 41.5%, 17.0%, 9.3%, and 5.9%, respectively. Since the operation of subtraction is faster than division, particularly for large numbers,[114] the subtraction-based Euclid’s algorithm is competitive with the division-based version.[115] This is exploited in the binary version of Euclid’s algorithm.[116]
Combining the estimated number of steps with the estimated computational expense per step shows that the Euclid’s algorithm grows quadratically (h2) with the average number of digits h in the initial two numbers a and b. Let h0, h1, …, hN−1 represent the number of digits in the successive remainders r0, r1, …, rN−1. Since the number of steps N grows linearly with h, the running time is bounded by
Alternative methods[edit]
Euclid’s algorithm is widely used in practice, especially for small numbers, due to its simplicity.[117] For comparison, the efficiency of alternatives to Euclid’s algorithm may be determined.
One inefficient approach to finding the GCD of two natural numbers a and b is to calculate all their common divisors; the GCD is then the largest common divisor. The common divisors can be found by dividing both numbers by successive integers from 2 to the smaller number b. The number of steps of this approach grows linearly with b, or exponentially in the number of digits. Another inefficient approach is to find the prime factors of one or both numbers. As noted above, the GCD equals the product of the prime factors shared by the two numbers a and b.[8] Present methods for prime factorization are also inefficient; many modern cryptography systems even rely on that inefficiency.[11]
The binary GCD algorithm is an efficient alternative that substitutes division with faster operations by exploiting the binary representation used by computers.[118][119] However, this alternative also scales like O(h²). It is generally faster than the Euclidean algorithm on real computers, even though it scales in the same way.[93] Additional efficiency can be gleaned by examining only the leading digits of the two numbers a and b.[120][121] The binary algorithm can be extended to other bases (k-ary algorithms),[122] with up to fivefold increases in speed.[123] Lehmer’s GCD algorithm uses the same general principle as the binary algorithm to speed up GCD computations in arbitrary bases.
A recursive approach for very large integers (with more than 25,000 digits) leads to quasilinear integer GCD algorithms,[124] such as those of Schönhage,[125][126] and Stehlé and Zimmermann.[127] These algorithms exploit the 2×2 matrix form of the Euclidean algorithm given above. These quasilinear methods generally scale as O(h (log h)2 (log log h)).[93][94]
Generalizations[edit]
Although the Euclidean algorithm is used to find the greatest common divisor of two natural numbers (positive integers), it may be generalized to the real numbers, and to other mathematical objects, such as polynomials,[128] quadratic integers[129] and Hurwitz quaternions.[130] In the latter cases, the Euclidean algorithm is used to demonstrate the crucial property of unique factorization, i.e., that such numbers can be factored uniquely into irreducible elements, the counterparts of prime numbers. Unique factorization is essential to many proofs of number theory.
Rational and real numbers[edit]
Euclid’s algorithm can be applied to real numbers, as described by Euclid in Book 10 of his Elements. The goal of the algorithm is to identify a real number g such that two given real numbers, a and b, are integer multiples of it: a = mg and b = ng, where m and n are integers.[28] This identification is equivalent to finding an integer relation among the real numbers a and b; that is, it determines integers s and t such that sa + tb = 0. If such an equation is possible, a and b are called commensurable lengths, otherwise they are incommensurable lengths.[131][132]
The real-number Euclidean algorithm differs from its integer counterpart in two respects. First, the remainders rk are real numbers, although the quotients qk are integers as before. Second, the algorithm is not guaranteed to end in a finite number N of steps. If it does, the fraction a/b is a rational number, i.e., the ratio of two integers
and can be written as a finite continued fraction [q0; q1, q2, …, qN]. If the algorithm does not stop, the fraction a/b is an irrational number and can be described by an infinite continued fraction [q0; q1, q2, …].[133] Examples of infinite continued fractions are the golden ratio φ = [1; 1, 1, …] and the square root of two, √2 = [1; 2, 2, …].[134] The algorithm is unlikely to stop, since almost all ratios a/b of two real numbers are irrational.[135]
An infinite continued fraction may be truncated at a step k [q0; q1, q2, …, qk] to yield an approximation to a/b that improves as k is increased. The approximation is described by convergents mk/nk; the numerator and denominators are coprime and obey the recurrence relation
where m−1 = n−2 = 1 and m−2 = n−1 = 0 are the initial values of the recursion. The convergent mk/nk is the best rational number approximation to a/b with denominator nk:[136]
Polynomials[edit]
Polynomials in a single variable x can be added, multiplied and factored into irreducible polynomials, which are the analogs of the prime numbers for integers. The greatest common divisor polynomial g(x) of two polynomials a(x) and b(x) is defined as the product of their shared irreducible polynomials, which can be identified using the Euclidean algorithm.[128] The basic procedure is similar to that for integers. At each step k, a quotient polynomial qk(x) and a remainder polynomial rk(x) are identified to satisfy the recursive equation
where r−2(x) = a(x) and r−1(x) = b(x). Each quotient polynomial is chosen such that each remainder is either zero or has a degree that is smaller than the degree of its predecessor: deg[rk(x)] < deg[rk−1(x)]. Since the degree is a nonnegative integer, and since it decreases with every step, the Euclidean algorithm concludes in a finite number of steps. The last nonzero remainder is the greatest common divisor of the original two polynomials, a(x) and b(x).[137]
For example, consider the following two quartic polynomials, which each factor into two quadratic polynomials
Dividing a(x) by b(x) yields a remainder r0(x) = x3 + (2/3)x2 + (5/3)x − (2/3). In the next step, b(x) is divided by r0(x) yielding a remainder r1(x) = x2 + x + 2. Finally, dividing r0(x) by r1(x) yields a zero remainder, indicating that r1(x) is the greatest common divisor polynomial of a(x) and b(x), consistent with their factorization.
Many of the applications described above for integers carry over to polynomials.[138] The Euclidean algorithm can be used to solve linear Diophantine equations and Chinese remainder problems for polynomials; continued fractions of polynomials can also be defined.
The polynomial Euclidean algorithm has other applications, such as Sturm chains, a method for counting the zeros of a polynomial that lie inside a given real interval.[139] This in turn has applications in several areas, such as the Routh–Hurwitz stability criterion in control theory.[140]
Finally, the coefficients of the polynomials need not be drawn from integers, real numbers or even the complex numbers. For example, the coefficients may be drawn from a general field, such as the finite fields GF(p) described above. The corresponding conclusions about the Euclidean algorithm and its applications hold even for such polynomials.[128]
Gaussian integers[edit]
Distribution of Gaussian primes u + vi in the complex plane, with norms u2 + v2 less than 500
The Gaussian integers are complex numbers of the form α = u + vi, where u and v are ordinary integers[note 2] and i is the square root of negative one.[141] By defining an analog of the Euclidean algorithm, Gaussian integers can be shown to be uniquely factorizable, by the argument above.[42] This unique factorization is helpful in many applications, such as deriving all Pythagorean triples or proving Fermat’s theorem on sums of two squares.[141] In general, the Euclidean algorithm is convenient in such applications, but not essential; for example, the theorems can often be proven by other arguments.
The Euclidean algorithm developed for two Gaussian integers α and β is nearly the same as that for ordinary integers,[142] but differs in two respects. As before, we set r−2 = α and r−1 = β, and the task at each step k is to identify a quotient qk and a remainder rk such that
where every remainder is strictly smaller than its predecessor: |rk| < |rk−1|. The first difference is that the quotients and remainders are themselves Gaussian integers, and thus are complex numbers. The quotients qk are generally found by rounding the real and complex parts of the exact ratio (such as the complex number α/β) to the nearest integers.[142] The second difference lies in the necessity of defining how one complex remainder can be “smaller” than another. To do this, a norm function f(u + vi) = u2 + v2 is defined, which converts every Gaussian integer u + vi into an ordinary integer. After each step k of the Euclidean algorithm, the norm of the remainder f(rk) is smaller than the norm of the preceding remainder, f(rk−1). Since the norm is a nonnegative integer and decreases with every step, the Euclidean algorithm for Gaussian integers ends in a finite number of steps.[143] The final nonzero remainder is gcd(α, β), the Gaussian integer of largest norm that divides both α and β; it is unique up to multiplication by a unit, ±1 or ±i.[144]
Many of the other applications of the Euclidean algorithm carry over to Gaussian integers. For example, it can be used to solve linear Diophantine equations and Chinese remainder problems for Gaussian integers;[145] continued fractions of Gaussian integers can also be defined.[142]
Euclidean domains[edit]
A set of elements under two binary operations, denoted as addition and multiplication, is called a Euclidean domain if it forms a commutative ring R and, roughly speaking, if a generalized Euclidean algorithm can be performed on them.[146][147] The two operations of such a ring need not be the addition and multiplication of ordinary arithmetic; rather, they can be more general, such as the operations of a mathematical group or monoid. Nevertheless, these general operations should respect many of the laws governing ordinary arithmetic, such as commutativity, associativity and distributivity.
The generalized Euclidean algorithm requires a Euclidean function, i.e., a mapping f from R into the set of nonnegative integers such that, for any two nonzero elements a and b in R, there exist q and r in R such that a = qb + r and f(r) < f(b).[148] Examples of such mappings are the absolute value for integers, the degree for univariate polynomials, and the norm for Gaussian integers above.[149][150] The basic principle is that each step of the algorithm reduces f inexorably; hence, if f can be reduced only a finite number of times, the algorithm must stop in a finite number of steps. This principle relies on the well-ordering property of the non-negative integers, which asserts that every non-empty set of non-negative integers has a smallest member.[151]
The fundamental theorem of arithmetic applies to any Euclidean domain: Any number from a Euclidean domain can be factored uniquely into irreducible elements. Any Euclidean domain is a unique factorization domain (UFD), although the converse is not true.[151] The Euclidean domains and the UFD’s are subclasses of the GCD domains, domains in which a greatest common divisor of two numbers always exists.[152] In other words, a greatest common divisor may exist (for all pairs of elements in a domain), although it may not be possible to find it using a Euclidean algorithm. A Euclidean domain is always a principal ideal domain (PID), an integral domain in which every ideal is a principal ideal.[153] Again, the converse is not true: not every PID is a Euclidean domain.
The unique factorization of Euclidean domains is useful in many applications. For example, the unique factorization of the Gaussian integers is convenient in deriving formulae for all Pythagorean triples and in proving Fermat’s theorem on sums of two squares.[141] Unique factorization was also a key element in an attempted proof of Fermat’s Last Theorem published in 1847 by Gabriel Lamé, the same mathematician who analyzed the efficiency of Euclid’s algorithm, based on a suggestion of Joseph Liouville.[154] Lamé’s approach required the unique factorization of numbers of the form x + ωy, where x and y are integers, and ω = e2iπ/n is an nth root of 1, that is, ωn = 1. Although this approach succeeds for some values of n (such as n = 3, the Eisenstein integers), in general such numbers do not factor uniquely. This failure of unique factorization in some cyclotomic fields led Ernst Kummer to the concept of ideal numbers and, later, Richard Dedekind to ideals.[155]
Unique factorization of quadratic integers[edit]
Distribution of Eisenstein primes u + vω in the complex plane, with norms less than 500. The number ω is a cube root of 1.
The quadratic integer rings are helpful to illustrate Euclidean domains. Quadratic integers are generalizations of the Gaussian integers in which the imaginary unit i is replaced by a number ω. Thus, they have the form u + vω, where u and v are integers and ω has one of two forms, depending on a parameter D. If D does not equal a multiple of four plus one, then
If, however, D does equal a multiple of four plus one, then
If the function f corresponds to a norm function, such as that used to order the Gaussian integers above, then the domain is known as norm-Euclidean. The norm-Euclidean rings of quadratic integers are exactly those where D is one of the values −11, −7, −3, −2, −1, 2, 3, 5, 6, 7, 11, 13, 17, 19, 21, 29, 33, 37, 41, 57, or 73.[156][157] The cases D = −1 and D = −3 yield the Gaussian integers and Eisenstein integers, respectively.
If f is allowed to be any Euclidean function, then the list of possible values of D for which the domain is Euclidean is not yet known.[158] The first example of a Euclidean domain that was not norm-Euclidean (with D = 69) was published in 1994.[158] In 1973, Weinberger proved that a quadratic integer ring with D > 0 is Euclidean if, and only if, it is a principal ideal domain, provided that the generalized Riemann hypothesis holds.[129]
Noncommutative rings[edit]
The Euclidean algorithm may be applied to some noncommutative rings such as the set of Hurwitz quaternions.[clarification needed][130] Let α and β represent two elements from such a ring. They have a common right divisor δ if α = ξδ and β = ηδ for some choice of ξ and η in the ring. Similarly, they have a common left divisor if α = dξ and β = dη for some choice of ξ and η in the ring. Since multiplication is not commutative, there are two versions of the Euclidean algorithm, one for right divisors and one for left divisors.[130] Choosing the right divisors, the first step in finding the gcd(α, β) by the Euclidean algorithm can be written
where ψ0 represents the quotient and ρ0 the remainder.[clarification needed] This equation shows that any common right divisor of α and β is likewise a common divisor of the remainder ρ0. The analogous equation for the left divisors would be
With either choice, the process is repeated as above until the greatest common right or left divisor is identified. As in the Euclidean domain, the “size” of the remainder ρ0 (formally, its norm) must be strictly smaller than β, and there must be only a finite number of possible sizes for ρ0, so that the algorithm is guaranteed to terminate.[159]
Most of the results for the GCD carry over to noncommutative numbers.[clarification needed] For example, Bézout’s identity states that the right gcd(α, β) can be expressed as a linear combination of α and β.[160] In other words, there are numbers σ and τ such that
The analogous identity for the left GCD is nearly the same:
Bézout’s identity can be used to solve Diophantine equations. For instance, one of the standard proofs of Lagrange’s four-square theorem, that every positive integer can be represented as a sum of four squares, is based on quaternion GCDs in this way.[159]
See also[edit]
- Euclidean rhythm, a method for using the Euclidean algorithm to generate musical rhythms
Notes[edit]
- ^ Some widely used textbooks, such as I. N. Herstein’s Topics in Algebra and Serge Lang’s Algebra, use the term “Euclidean algorithm” to refer to Euclidean division
- ^ The phrase “ordinary integer” is commonly used for distinguishing usual integers from Gaussian integers, and more generally from algebraic integers.
References[edit]
- ^ Lamé, Gabriel (1844). “Note sur la limite du nombre des divisions dans la recherche du plus grand commun diviseur entre deux nombres entiers”. Comptes rendus des séances du l’Académie des Sciences (in French). 19: 867–870.
- ^ Shallit, Jeffrey (1994-11-01). “Origins of the analysis of the Euclidean algorithm”. Historia Mathematica. 21 (4): 401–419. doi:10.1006/hmat.1994.1031. ISSN 0315-0860.
- ^ Stark 1978, p. 16
- ^ Stark 1978, p. 21
- ^ LeVeque 1996, p. 32
- ^ LeVeque 1996, p. 31
- ^ Grossman, J. W. (1990). Discrete Mathematics. New York: Macmillan. p. 213. ISBN 0-02-348331-8.
- ^ a b Schroeder 2005, pp. 21–22
- ^ Schroeder 2005, p. 19
- ^ Ogilvy, C. S.; Anderson, J. T. (1966). Excursions in number theory. New York: Oxford University Press. pp. 27–29.
- ^ a b Schroeder 2005, pp. 216–219
- ^ a b LeVeque 1996, p. 33
- ^ Stark 1978, p. 25
- ^ Ore 1948, pp. 47–48
- ^ Stark 1978, p. 18
- ^ Stark 1978, pp. 16–20
- ^ Knuth 1997, p. 320
- ^ Lovász, L.; Pelikán, J.; Vesztergombi, K. (2003). Discrete Mathematics: Elementary and Beyond. New York: Springer-Verlag. pp. 100–101. ISBN 0-387-95584-4.
- ^ Kimberling, C. (1983). “A Visual Euclidean Algorithm”. Mathematics Teacher. 76: 108–109.
- ^ Dummit, David S.; Foote, Richard M. (2004). Abstract Algebra. John Wiley & Sons, Inc. pp. 270–271. ISBN 978-0-471-43334-7.
- ^ Knuth 1997, pp. 319–320
- ^ Knuth 1997, pp. 318–319
- ^ Stillwell 1997, p. 14
- ^ a b Ore 1948, p. 43
- ^ a b Stewart, B. M. (1964). Theory of Numbers (2nd ed.). New York: Macmillan. pp. 43–44. LCCN 64010964.
- ^ Lazard, D. (1977). “Le meilleur algorithme d’Euclide pour K[X] et Z“. Comptes rendus de l’Académie des Sciences (in French). 284: 1–4.
- ^ a b Knuth 1997, p. 318
- ^ a b Weil, A. (1983). Number Theory. Boston: Birkhäuser. pp. 4–6. ISBN 0-8176-3141-0.
- ^ Jones, A. (1994). “Greek mathematics to AD 300”. Companion encyclopedia of the history and philosophy of the mathematical sciences. New York: Routledge. pp. 46–48. ISBN 0-415-09238-8.
- ^ van der Waerden, B. L. (1954). Science Awakening. translated by Arnold Dresden. Groningen: P. Noordhoff Ltd. pp. 114–115.
- ^ von Fritz, K. (1945). “The Discovery of Incommensurability by Hippasus of Metapontum”. Annals of Mathematics. 46 (2): 242–264. doi:10.2307/1969021. JSTOR 1969021.
- ^ Heath, T. L. (1949). Mathematics in Aristotle. Oxford Press. pp. 80–83.
- ^ Fowler, D. H. (1987). The Mathematics of Plato’s Academy: A New Reconstruction. Oxford: Oxford University Press. pp. 31–66. ISBN 0-19-853912-6.
- ^ Becker, O. (1933). “Eudoxus-Studien I. Eine voreuklidische Proportionslehre und ihre Spuren bei Aristoteles und Euklid”. Quellen und Studien zur Geschichte der Mathematik B. 2: 311–333.
- ^ a b Stillwell 1997, p. 31
- ^ a b Tattersall 2005, p. 70
- ^ Rosen 2000, pp. 86–87
- ^ Ore 1948, pp. 247–248
- ^ Tattersall 2005, pp. 72, 184–185
- ^ Saunderson, Nicholas (1740). The Elements of Algebra in Ten Books. University of Cambridge Press. Retrieved 1 November 2016.
- ^ Tattersall 2005, pp. 72–76
- ^ a b Gauss, C. F. (1832). “Theoria residuorum biquadraticorum”. Comm. Soc. Reg. Sci. Gött. Rec. 4. Reprinted in Gauss, C. F. (2011). “Theoria residuorum biquadraticorum commentatio prima”. Werke. Vol. 2. Cambridge Univ. Press. pp. 65–92. doi:10.1017/CBO9781139058230.004. ISBN 9781139058230. and Gauss, C. F. (2011). “Theoria residuorum biquadraticorum commentatio secunda”. Werke. Vol. 2. Cambridge Univ. Press. pp. 93–148. doi:10.1017/CBO9781139058230.005. ISBN 9781139058230.
- ^ Stillwell 1997, pp. 31–32
- ^ Lejeune Dirichlet 1894, pp. 29–31
- ^ Richard Dedekind in Lejeune Dirichlet 1894, Supplement XI
- ^ Stillwell 2003, pp. 41–42
- ^ Sturm, C. (1829). “Mémoire sur la résolution des équations numériques”. Bull. Des sciences de Férussac (in French). 11: 419–422.
- ^ Ferguson, H. R. P.; Forcade, R. W. (1979). “Generalization of the Euclidean algorithm for real numbers to all dimensions higher than two”. Bulletin of the American Mathematical Society. New Series. 1 (6): 912–914. doi:10.1090/S0273-0979-1979-14691-3. MR 0546316.
- ^ Peterson, I. (12 August 2002). “Jazzing Up Euclid’s Algorithm”. ScienceNews.
- ^ Cipra, Barry Arthur (16 May 2000). “The Best of the 20th Century: Editors Name Top 10 Algorithms” (PDF). SIAM News. Society for Industrial and Applied Mathematics. 33 (4). Archived from the original (PDF) on 22 September 2016. Retrieved 19 July 2016.
- ^ Cole, A. J.; Davie, A. J. T. (1969). “A game based on the Euclidean algorithm and a winning strategy for it”. Math. Gaz. 53 (386): 354–357. doi:10.2307/3612461. JSTOR 3612461. S2CID 125164797.
- ^ Spitznagel, E. L. (1973). “Properties of a game based on Euclid’s algorithm”. Math. Mag. 46 (2): 87–92. doi:10.2307/2689037. JSTOR 2689037.
- ^ Rosen 2000, p. 95
- ^ Roberts, J. (1977). Elementary Number Theory: A Problem Oriented Approach. Cambridge, MA: MIT Press. pp. 1–8. ISBN 0-262-68028-9.
- ^ Jones, G. A.; Jones, J. M. (1998). “Bezout’s Identity”. Elementary Number Theory. New York: Springer-Verlag. pp. 7–11.
- ^ Rosen 2000, p. 81
- ^ Cohn 1962, p. 104
- ^ Rosen 2000, p. 91
- ^ Schroeder 2005, p. 23
- ^ Rosen 2000, pp. 90–93
- ^ a b Koshy, T. (2002). Elementary Number Theory with Applications. Burlington, MA: Harcourt/Academic Press. pp. 167–169. ISBN 0-12-421171-2.
- ^ Bach, E.; Shallit, J. (1996). Algorithmic number theory. Cambridge, MA: MIT Press. pp. 70–73. ISBN 0-262-02405-5.
- ^ Stark 1978, pp. 26–36
- ^ a b Ore 1948, p. 44
- ^ Stark 1978, pp. 281–292
- ^ Rosen 2000, pp. 119–125
- ^ Schroeder 2005, pp. 106–107
- ^ Schroeder 2005, pp. 108–109
- ^ Rosen 2000, pp. 120–121
- ^ Stark 1978, p. 47
- ^ Schroeder 2005, pp. 107–109
- ^ Stillwell 1997, pp. 186–187
- ^ Schroeder 2005, p. 134
- ^ Moon, T. K. (2005). Error Correction Coding: Mathematical Methods and Algorithms. John Wiley and Sons. p. 266. ISBN 0-471-64800-0.
- ^ Rosen 2000, pp. 143–170
- ^ Schroeder 2005, pp. 194–195
- ^ Graham, R.; Knuth, D. E.; Patashnik, O. (1989). Concrete mathematics. Addison-Wesley. p. 123.
- ^ Vinogradov, I. M. (1954). Elements of Number Theory. New York: Dover. pp. 3–13.
- ^ Crandall & Pomerance 2001, pp. 225–349
- ^ Knuth 1997, pp. 369–371
- ^ Shor, P. W. (1997). “Polynomial-Time Algorithms for Prime Factorization and Discrete Logarithms on a Quantum Computer”. SIAM Journal on Scientific and Statistical Computing. 26 (5): 1484–1509. arXiv:quant-ph/9508027. Bibcode:1995quant.ph..8027S. doi:10.1137/s0097539795293172. S2CID 2337707.
- ^ Dixon, J. D. (1981). “Asymptotically fast factorization of integers”. Math. Comput. 36 (153): 255–260. doi:10.2307/2007743. JSTOR 2007743.
- ^ Lenstra, H. W. Jr. (1987). “Factoring integers with elliptic curves”. Annals of Mathematics. 126 (3): 649–673. doi:10.2307/1971363. hdl:1887/2140. JSTOR 1971363.
- ^ Knuth 1997, pp. 380–384
- ^ Knuth 1997, pp. 339–364
- ^ Reynaud, A.-A.-L. (1811). Traité d’arithmétique à l’usage des élèves qui se destinent à l’École Polytechnique (6th ed.). Paris: Courcier. Note 60, p. 34. As cited by Shallit (1994) harvtxt error: multiple targets (2×): CITEREFShallit1994 (help).
- ^ Finck, P.-J.-E. (1841). Traité élémentaire d’arithmétique à l’usage des candidats aux écoles spéciales (in French). Derivaux.
- ^ a b Shallit, J. (1994). “Origins of the analysis of the Euclidean algorithm”. Historia Math. 21 (4): 401–419. doi:10.1006/hmat.1994.1031.
- ^ Lamé, G. (1844). “Note sur la limite du nombre des divisions dans la recherche du plus grand commun diviseur entre deux nombres entiers”. Comptes Rendus Acad. Sci. (in French). 19: 867–870.
- ^ Grossman, H. (1924). “On the Number of Divisions in Finding a G.C.D”. The American Mathematical Monthly. 31 (9): 443. doi:10.2307/2298146. JSTOR 2298146.
- ^ Honsberger, R. (1976). Mathematical Gems II. The Mathematical Association of America. pp. 54–57. ISBN 0-88385-302-7.
- ^ a b Knuth 1997, pp. 257–261
- ^ a b c Crandall & Pomerance 2001, pp. 77–79, 81–85, 425–431
- ^ a b Möller, N. (2008). “On Schönhage’s algorithm and subquadratic integer gcd computation” (PDF). Mathematics of Computation. 77 (261): 589–607. Bibcode:2008MaCom..77..589M. doi:10.1090/S0025-5718-07-02017-0.
- ^ a b c Knuth 1997, p. 344
- ^ Ore 1948, p. 45
- ^ a b Knuth 1997, p. 343
- ^ Mollin 2008, p. 21
- ^ LeVeque 1996, p. 35
- ^ Mollin 2008, pp. 21–22
- ^ Knuth 1997, p. 353
- ^ Knuth 1997, p. 357
- ^ Tonkov, T. (1974). “On the average length of finite continued fractions”. Acta Arithmetica. 26: 47–57. doi:10.4064/aa-26-1-47-57.
- ^ Knuth, Donald E. (1976). “Evaluation of Porter’s constant”. Computers & Mathematics with Applications. 2 (2): 137–139. doi:10.1016/0898-1221(76)90025-0.
- ^ Porter, J. W. (1975). “On a Theorem of Heilbronn”. Mathematika. 22: 20–28. doi:10.1112/S0025579300004459.
- ^ Knuth, D. E. (1976). “Evaluation of Porter’s Constant”. Computers and Mathematics with Applications. 2 (2): 137–139. doi:10.1016/0898-1221(76)90025-0.
- ^ Dixon, J. D. (1970). “The Number of Steps in the Euclidean Algorithm”. J. Number Theory. 2 (4): 414–422. Bibcode:1970JNT…..2..414D. doi:10.1016/0022-314X(70)90044-2.
- ^ Heilbronn, H. A. (1969). “On the Average Length of a Class of Finite Continued Fractions”. In Paul Turán (ed.). Number Theory and Analysis. New York: Plenum. pp. 87–96. LCCN 76016027.
- ^ Knuth 1997, p. 354
- ^ a b Norton, G. H. (1990). “On the Asymptotic Analysis of the Euclidean Algorithm”. Journal of Symbolic Computation. 10: 53–58. doi:10.1016/S0747-7171(08)80036-3.
- ^ Knuth 1997, p. 355
- ^ Knuth 1997, p. 356
- ^ Knuth 1997, p. 352
- ^ Wagon, S. (1999). Mathematica in Action. New York: Springer-Verlag. pp. 335–336. ISBN 0-387-98252-3.
- ^ Cohen 1993, p. 14
- ^ Cohen 1993, pp. 14–15, 17–18
- ^ Sorenson, Jonathan P. (2004). “An analysis of the generalized binary GCD algorithm”. High primes and misdemeanours: lectures in honour of the 60th birthday of Hugh Cowie Williams. Fields Institute Communications. Vol. 41. Providence, RI: American Mathematical Society. pp. 327–340. ISBN 9780821887592. MR 2076257.
The algorithms that are used the most in practice today [for computing greatest common divisors] are probably the binary algorithm and Euclid’s algorithm for smaller numbers, and either Lehmer’s algorithm or Lebealean’s version of the k-ary GCD algorithm for larger numbers.
- ^ Knuth 1997, pp. 321–323
- ^ Stein, J. (1967). “Computational problems associated with Racah algebra”. Journal of Computational Physics. 1 (3): 397–405. Bibcode:1967JCoPh…1..397S. doi:10.1016/0021-9991(67)90047-2.
- ^ Knuth 1997, p. 328
- ^ Lehmer, D. H. (1938). “Euclid’s Algorithm for Large Numbers”. The American Mathematical Monthly. 45 (4): 227–233. doi:10.2307/2302607. JSTOR 2302607.
- ^ Sorenson, J. (1994). “Two fast GCD algorithms”. J. Algorithms. 16: 110–144. doi:10.1006/jagm.1994.1006.
- ^ Weber, K. (1995). “The accelerated GCD algorithm”. ACM Trans. Math. Softw. 21: 111–122. doi:10.1145/200979.201042. S2CID 14934919.
- ^ Aho, A.; Hopcroft, J.; Ullman, J. (1974). The Design and Analysis of Computer Algorithms. New York: Addison–Wesley. pp. 300–310. ISBN 0-201-00029-6.
- ^ Schönhage, A. (1971). “Schnelle Berechnung von Kettenbruchentwicklungen”. Acta Informatica (in German). 1 (2): 139–144. doi:10.1007/BF00289520. S2CID 34561609.
- ^ Cesari, G. (1998). “Parallel implementation of Schönhage’s integer GCD algorithm”. In G. Buhler (ed.). Algorithmic Number Theory: Proc. ANTS-III, Portland, OR. Lecture Notes in Computer Science. Vol. 1423. New York: Springer-Verlag. pp. 64–76.
- ^ Stehlé, D.; Zimmermann, P. (2005). “Gal’s accurate tables method revisited”. Proceedings of the 17th IEEE Symposium on Computer Arithmetic (ARITH-17). Los Alamitos, CA: IEEE Computer Society Press.
- ^ a b c Lang, S. (1984). Algebra (2nd ed.). Menlo Park, CA: Addison–Wesley. pp. 190–194. ISBN 0-201-05487-6.
- ^ a b Weinberger, P. (1973). “On Euclidean rings of algebraic integers”. Proc. Sympos. Pure Math. Proceedings of Symposia in Pure Mathematics. 24: 321–332. doi:10.1090/pspum/024/0337902. ISBN 9780821814246.
- ^ a b c Stillwell 2003, pp. 151–152
- ^ Boyer, C. B.; Merzbach, U. C. (1991). A History of Mathematics (2nd ed.). New York: Wiley. pp. 116–117. ISBN 0-471-54397-7.
- ^ Cajori, F (1894). A History of Mathematics. New York: Macmillan. p. 70. ISBN 0-486-43874-0.
- ^ Joux, Antoine (2009). Algorithmic Cryptanalysis. CRC Press. p. 33. ISBN 9781420070033.
- ^ Fuks, D. B.; Tabachnikov, Serge (2007). Mathematical Omnibus: Thirty Lectures on Classic Mathematics. American Mathematical Society. p. 13. ISBN 9780821843161.
- ^ Darling, David (2004). “Khintchine’s constant”. The Universal Book of Mathematics: From Abracadabra to Zeno’s Paradoxes. John Wiley & Sons. p. 175. ISBN 9780471667001.
- ^ Williams, Colin P. (2010). Explorations in Quantum Computing. Springer. pp. 277–278. ISBN 9781846288876.
- ^ Cox, Little & O’Shea 1997, pp. 37–46
- ^ Schroeder 2005, pp. 254–259
- ^ Grattan-Guinness, Ivor (1990). Convolutions in French Mathematics, 1800-1840: From the Calculus and Mechanics to Mathematical Analysis and Mathematical Physics. Volume II: The Turns. Science Networks: Historical Studies. Vol. 3. Basel, Boston, Berlin: Birkhäuser. p. 1148. ISBN 9783764322380.
Our subject here is the ‘Sturm sequence’ of functions defined from a function and its derivative by means of Euclid’s algorithm, in order to calculate the number of real roots of a polynomial within a given interval
- ^ Hairer, Ernst; Nørsett, Syvert P.; Wanner, Gerhard (1993). “The Routh–Hurwitz Criterion”. Solving Ordinary Differential Equations I: Nonstiff Problems. Springer Series in Computational Mathematics. Vol. 8 (2nd ed.). Springer. pp. 81ff. ISBN 9783540566700.
- ^ a b c Stillwell 2003, pp. 101–116
- ^ a b c Hensley, Doug (2006). Continued Fractions. World Scientific. p. 26. ISBN 9789812564771.
- ^ Dedekind, Richard (1996). Theory of Algebraic Integers. Cambridge Mathematical Library. Cambridge University Press. pp. 22–24. ISBN 9780521565189.
- ^ Johnston, Bernard L.; Richman, Fred (1997). Numbers and Symmetry: An Introduction to Algebra. CRC Press. p. 44. ISBN 9780849303012.
- ^ Adams, William W.; Goldstein, Larry Joel (1976). Introduction to Number Theory. Prentice-Hall. Exercise 24, p. 205. ISBN 9780134912820.
State and prove an analogue of the Chinese remainder theorem for the Gaussian integers.
- ^ Stark 1978, p. 290
- ^ Cohn 1962, pp. 104–105
- ^ Lauritzen, Niels (2003). Concrete Abstract Algebra: From Numbers to Gröbner Bases. Cambridge University Press. p. 130. ISBN 9780521534109.
- ^ Lauritzen (2003), p. 132
- ^ Lauritzen (2003), p. 161
- ^ a b Sharpe, David (1987). Rings and Factorization. Cambridge University Press. p. 55. ISBN 9780521337182.
- ^ Sharpe (1987), p. 52
- ^ Lauritzen (2003), p. 131
- ^ Lamé, G. (1847). “Mémoire sur la résolution, en nombres complexes, de l’équation An + Bn + Cn = 0″. J. Math. Pures Appl. (in French). 12: 172–184.
- ^ Edwards, H. (2000). Fermat’s last theorem: a genetic introduction to algebraic number theory. Springer. p. 76.
- ^ Cohn 1962, pp. 104–110
- ^ LeVeque, W. J. (2002) [1956]. Topics in Number Theory, Volumes I and II. New York: Dover Publications. pp. II:57, 81. ISBN 978-0-486-42539-9. Zbl 1009.11001.
- ^ a b Clark, D. A. (1994). “A quadratic field which is Euclidean but not norm-Euclidean”. Manuscripta Mathematica. 83: 327–330. doi:10.1007/BF02567617. S2CID 895185. Zbl 0817.11047.
- ^ a b Davidoff, Giuliana; Sarnak, Peter; Valette, Alain (2003). “2.6 The Arithmetic of Integer Quaternions”. Elementary Number Theory, Group Theory and Ramanujan Graphs. London Mathematical Society Student Texts. Vol. 55. Cambridge University Press. pp. 59–70. ISBN 9780521531436.
- ^ Ribenboim, Paulo (2001). Classical Theory of Algebraic Numbers. Universitext. Springer-Verlag. p. 104. ISBN 9780387950709.
Bibliography[edit]
- Cohen, H. (1993). A Course in Computational Algebraic Number Theory. New York: Springer-Verlag. ISBN 0-387-55640-0.
- Cohn, H. (1962). Advanced Number Theory. New York: Dover. ISBN 0-486-64023-X.
- Cox, D.; Little, J.; O’Shea, D. (1997). Ideals, Varieties, and Algorithms: An Introduction to Computational Algebraic Geometry and Commutative Algebra (2nd ed.). Springer-Verlag. ISBN 0-387-94680-2.
- Crandall, R.; Pomerance, C. (2001). Prime Numbers: A Computational Perspective (1st ed.). New York: Springer-Verlag. ISBN 0-387-94777-9.
- Lejeune Dirichlet, P. G. (1894). Dedekind, Richard (ed.). Vorlesungen über Zahlentheorie (Lectures on Number Theory) (in German). Braunschweig: Vieweg. LCCN 03005859. OCLC 490186017.. See also Vorlesungen über Zahlentheorie
- Knuth, D. E. (1997). The Art of Computer Programming, Volume 2: Seminumerical Algorithms (3rd ed.). Addison–Wesley. ISBN 0-201-89684-2.
- LeVeque, W. J. (1996) [1977]. Fundamentals of Number Theory. New York: Dover. ISBN 0-486-68906-9.
- Mollin, R. A. (2008). Fundamental Number Theory with Applications (2nd ed.). Boca Raton: Chapman & Hall/CRC. ISBN 978-1-4200-6659-3.
- Ore, O. (1948). Number Theory and Its History. New York: McGraw–Hill.
- Rosen, K. H. (2000). Elementary Number Theory and its Applications (4th ed.). Reading, MA: Addison–Wesley. ISBN 0-201-87073-8.
- Schroeder, M. (2005). Number Theory in Science and Communication (4th ed.). Springer-Verlag. ISBN 0-387-15800-6.
- Stark, H. (1978). An Introduction to Number Theory. MIT Press. ISBN 0-262-69060-8.
- Stillwell, J. (1997). Numbers and Geometry. New York: Springer-Verlag. ISBN 0-387-98289-2.
- Stillwell, J. (2003). Elements of Number Theory. New York: Springer-Verlag. ISBN 0-387-95587-9.
- Tattersall, J. J. (2005). Elementary Number Theory in Nine Chapters. Cambridge: Cambridge University Press. ISBN 978-0-521-85014-8.
External links[edit]
- Demonstrations of Euclid’s algorithm
- Weisstein, Eric W. “Euclidean Algorithm”. MathWorld.
- Euclid’s Algorithm at cut-the-knot
- Euclid’s algorithm at PlanetMath.
- The Euclidean Algorithm at MathPages
- Euclid’s Game at cut-the-knot
- Music and Euclid’s algorithm