Skip to content

Commit cd8d778

Browse files
authored
Update euclid-algorithm.md
Add 'GCD of multiple numbers' section.
1 parent b319183 commit cd8d778

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/algebra/euclid-algorithm.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,30 @@ 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+
91115
## Binary GCD
92116

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

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy