You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/algebra/euclid-algorithm.md
+1-26Lines changed: 1 addition & 26 deletions
Original file line number
Diff line number
Diff line change
@@ -15,7 +15,7 @@ $$\gcd(a, b) = \max \{k > 0 : (k \mid a) \text{ and } (k \mid b) \}$$
15
15
16
16
When one of the numbers is zero, while the other is non-zero, their greatest common divisor, by definition, is the second number. When both numbers are zero, their greatest common divisor is undefined (it can be any arbitrarily large number), but it is convenient to define it as zero as well to preserve the associativity of $\gcd$. Which gives us a simple rule: if one of the numbers is zero, the greatest common divisor is the other number.
17
17
18
-
The Euclidean algorithm, discussed below, allows to find the greatest common divisor of two numbers $a$ and $b$ in $O(\log \min(a, b))$.
18
+
The Euclidean algorithm, discussed below, allows to find the greatest common divisor of two numbers $a$ and $b$ in $O(\log \min(a, b))$. Since the function is**associative**, to find the GCD of**more than two numbers**, we can do $\gcd(a, b, c) = \gcd(a, \gcd(b, c))$ and so forth.
19
19
20
20
The algorithm was first described in Euclid's "Elements" (circa 300 BC), but it is possible that the algorithm has even earlier origins.
21
21
@@ -87,31 +87,6 @@ int lcm (int a, int b) {
87
87
return a / gcd(a, b) * b;
88
88
}
89
89
```
90
-
91
-
##GCD of multiple numbers
92
-
93
-
Given an array of more than two integers, your task is to find the GCD of these integers, which is the largest number that divides**all** of them.
94
-
95
-
A simple way to achieve this is to calculate the GCD of each integer with the previous GCD result:
96
-
97
-
```cpp
98
-
// a[0..n-1]
99
-
int res = a[0];
100
-
for (int i =1; i < n; ++i) {
101
-
res = gcd(res, a[i]);
102
-
}
103
-
```
104
-
105
-
It's also possible to interrupt the loop earlier by checking if`res` is equal to 1:
106
-
107
-
```cpp
108
-
int res = a[0];
109
-
for (int i =1; i < n; ++i) {
110
-
if (res == 1) break;
111
-
res = gcd(res, a[i]);
112
-
}
113
-
```
114
-
115
90
##Binary GCD
116
91
117
92
The Binary GCD algorithm is an optimization to the normal Euclidean algorithm.