File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff 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+ ```
Original file line number Diff line number Diff 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+ ```
You can’t perform that action at this time.
0 commit comments