File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 最大公約数(gcd)と最小公倍数(lcm)
2
+
3
+ C++17ではヘッダーファイル\< numeric\> に最大公約数(gcd)と最小公倍数(lcm)が追加された。
4
+
5
+ ~~~ cpp
6
+ int main ()
7
+ {
8
+ int a, b ;
9
+
10
+ while( std::cin >> a >> b )
11
+ {
12
+ std::cout
13
+ << "gcd: " << gcd(a,b)
14
+ << "\nlcm: " << lcm(a,b) << '\n' ;
15
+ }
16
+ }
17
+ ~~~
18
+
19
+ ### gcd : 最大公約数
20
+
21
+ ~~~ c++
22
+ template <class M , class N>
23
+ constexpr std::common_type_t<M,N> gcd(M m, N n)
24
+ {
25
+ if ( n == 0 )
26
+ return m ;
27
+ else
28
+ return gcd( n, std::abs(m) % std::abs(n) ) ;
29
+ }
30
+ ~~~
31
+
32
+ gcd(m, n)はmとnがともにゼロの場合ゼロを返す。それ以外の場合、$\abs{m}$と$\abs{n}$の最大公約数(Greatest Common Divisor)を返す。
33
+
34
+ ### lcm : 最小公倍数
35
+
36
+ ~~~c++
37
+ template <class M, class N>
38
+ constexpr std::common_type_t<M,N> lcm(M m, N n)
39
+ {
40
+ if ( m == 0 || n == 0 )
41
+ return 0 ;
42
+ else
43
+ return std::abs(m) / gcd( m, n ) * std::abs(n) ;
44
+ }
45
+ ~~~
46
+
47
+ lcm(m,n)は、mとnのどちらかがゼロの場合ゼロを返す。それ以外の場合、$\abs{m}$と$\abs{n}$の最小公倍数(Least Common Multiple)を返す。
You can’t perform that action at this time.
0 commit comments