General Utility Library for C++14  2.7
gcd_lcm.h
Go to the documentation of this file.
1 
23 #ifndef GUL14_GCD_LCM_H_
24 #define GUL14_GCD_LCM_H_
25 
26 #include <type_traits>
27 #include "gul14/internal.h"
28 #include "gul14/num_util.h"
29 
30 namespace gul14 {
31 
62 template <typename IntTypeA, typename IntTypeB>
63 constexpr inline auto
64 gcd(IntTypeA a, IntTypeB b)
65 {
66  static_assert(std::is_integral<IntTypeA>::value and std::is_integral<IntTypeB>::value,
67  "gcd() arguments must be integers");
68 
69  static_assert(std::is_signed<IntTypeA>::value == std::is_signed<IntTypeB>::value,
70  "gcd() arguments must have the same signedness");
71 
72  using CommonType = std::common_type_t<IntTypeA, IntTypeB>;
73 
74  auto c = gul14::abs(static_cast<CommonType>(a));
75  auto d = gul14::abs(static_cast<CommonType>(b));
76 
77  while (d != 0)
78  {
79  CommonType tmp = d;
80  d = c % d;
81  c = tmp;
82  }
83 
84  return c;
85 }
86 
116 template <typename IntTypeA, typename IntTypeB>
117 constexpr inline auto
118 lcm(IntTypeA a, IntTypeB b)
119 {
120  static_assert(std::is_integral<IntTypeA>::value and std::is_integral<IntTypeB>::value,
121  "lcm() arguments must be integers");
122 
123  static_assert(std::is_signed<IntTypeA>::value == std::is_signed<IntTypeB>::value,
124  "lcm() arguments must have the same signedness");
125 
126  using CommonType = std::common_type_t<IntTypeA, IntTypeB>;
127 
128  if (a == 0 && b == 0)
129  return CommonType{ 0 };
130 
131  return static_cast<CommonType>(gul14::abs((a / gcd(a, b)) * b));
132 }
133 
134 } // namespace gul14
135 
136 #endif
Definition of macros used internally by GUL.
Namespace gul14 contains all functions and classes of the General Utility Library.
Definition: doxygen.h:26
constexpr auto abs(ValueT n) noexcept -> std::enable_if_t< std::is_unsigned< ValueT >::value, ValueT >
Compute the absolute value of a number.
Definition: num_util.h:47
constexpr auto lcm(IntTypeA a, IntTypeB b)
Calculate the least common multiple of two integers.
Definition: gcd_lcm.h:118
constexpr auto gcd(IntTypeA a, IntTypeB b)
Calculate the greatest common divisor of two integers using the Euclidean algorithm.
Definition: gcd_lcm.h:64
Declarations of numerics utility functions for the General Utility Library.