Iros
 
Loading...
Searching...
No Matches
gcd.h
Go to the documentation of this file.
1#pragma once
2
4#include "di/meta/common.h"
5#include "di/meta/language.h"
6
7namespace di::math {
8namespace detail {
9 struct GcdFunction {
10 template<concepts::Integer T>
11 constexpr auto operator()(T) const {
12 return T(1);
13 }
14
15 template<concepts::Integer T, concepts::Integer U>
16 constexpr auto operator()(T m, U n) const {
17 using R = meta::CommonType<T, U>;
18
19 if (m == 0 || n == 0) {
20 return R(0);
21 }
22
23 using UR = meta::MakeUnsigned<R>;
24 UR a = abs_unsigned(m);
25 UR b = abs_unsigned(n);
26
27 while (a && b) {
28 if (a >= b) {
29 a = (a - b) % b;
30 } else {
31 b = (b - a) % a;
32 }
33 }
34 return a ? R(a) : R(b);
35 }
36
37 template<concepts::Integer T, concepts::Integer... Rest>
38 constexpr auto operator()(T m, Rest... rest) const {
39 return (*this)(m, (*this)(rest...));
40 }
41 };
42}
43
44constexpr inline auto gcd = detail::GcdFunction {};
45}
46
47namespace di {
48using math::gcd;
49}
Definition language.h:215
Definition abs.h:11
Definition abs.h:10
constexpr auto abs_unsigned
Definition abs_unsigned.h:26
constexpr auto gcd
Definition gcd.h:44
detail::CommonTypeHelper< Types... >::Type CommonType
Definition common.h:62
detail::MakeUnsignedHelper< RemoveCV< T > >::Type MakeUnsigned
Definition language.h:362
Definition zstring_parser.h:9
constexpr auto operator()(T m, Rest... rest) const
Definition gcd.h:38
constexpr auto operator()(T m, U n) const
Definition gcd.h:16
constexpr auto operator()(T) const
Definition gcd.h:11