Skip to content

Commit 5b5cd37

Browse files
committed
added a sample implementation for gcd and lcm function
1 parent f702e61 commit 5b5cd37

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

reference/numeric/gcd.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ int main() {
129129
```
130130
```
131131
132+
132133
## バージョン
133134
### 言語
134135
- C++17
@@ -167,3 +168,22 @@ $$ \mathrm{gcd}(m, n) = \begin{cases}
167168
|m| & \text{if } n = 0 \\
168169
\mathrm{gcd}(n, m \bmod n) & \text{otherwise}
169170
\end{cases} $$
171+
172+
173+
```cpp
174+
template <class M, class N>
175+
constexpr std::common_type_t<M, N> gcd(M m, N n) {
176+
if (m == 0 && n == 0) {
177+
return 0;
178+
}
179+
while (m != 0 && n != 0) {
180+
if (m > n) {
181+
m %= n;
182+
}
183+
else {
184+
n %= m;
185+
}
186+
}
187+
return m < n ? n : m;
188+
}
189+
```

reference/numeric/lcm.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,26 @@ int main() {
171171
172172
## 実装例
173173
$$ \mathrm{lcm}(m, n) = \frac{|mn|}{\mathrm{gcd}(m, n)} $$
174+
175+
```cpp
176+
template <class M, class N>
177+
constexpr std::common_type_t<M, N> gcd(M m, N n) {
178+
if (m == 0 && n == 0) {
179+
return 0;
180+
}
181+
while (m != 0 && n != 0) {
182+
if (m > n) {
183+
m %= n;
184+
}
185+
else {
186+
n %= m;
187+
}
188+
}
189+
return m < n ? n : m;
190+
}
191+
192+
template <class M, class N>
193+
constexpr std::common_type_t<M, N> lcm(M m, N n) {
194+
return m / gcd(m, n) * n;
195+
}
196+
```

0 commit comments

Comments
 (0)