Skip to content

Commit 1124c35

Browse files
committed
Update euclid-algorithm.md
1 parent cd8d778 commit 1124c35

File tree

1 file changed

+1
-25
lines changed

1 file changed

+1
-25
lines changed

src/algebra/euclid-algorithm.md

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ $$\gcd(a, b) = \max \{k > 0 : (k \mid a) \text{ and } (k \mid b) \}$$
1515

1616
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.
1717

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.
1919

2020
The algorithm was first described in Euclid's "Elements" (circa 300 BC), but it is possible that the algorithm has even earlier origins.
2121

@@ -88,30 +88,6 @@ int lcm (int a, int b) {
8888
}
8989
```
9090

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-
11591
## Binary GCD
11692

11793
The Binary GCD algorithm is an optimization to the normal Euclidean algorithm.

0 commit comments

Comments
 (0)