General Utility Library for C++17 26.5.0
gcd_lcm.h
Go to the documentation of this file.
1
26#ifndef GUL17_GCD_LCM_H_
27#define GUL17_GCD_LCM_H_
28
29#include <type_traits>
30
31#include "gul17/internal.h"
32#include "gul17/num_util.h"
33
34namespace gul17 {
35
72template <typename IntTypeA, typename IntTypeB>
73constexpr inline auto
75{
76 static_assert(std::is_integral<IntTypeA>::value and std::is_integral<IntTypeB>::value,
77 "gcd() arguments must be integers");
78
79 static_assert(std::is_signed<IntTypeA>::value == std::is_signed<IntTypeB>::value,
80 "gcd() arguments must have the same signedness");
81
82 using CommonType = std::common_type_t<IntTypeA, IntTypeB>;
83
84 auto c = gul17::abs(static_cast<CommonType>(a));
85 auto d = gul17::abs(static_cast<CommonType>(b));
86
87 while (d != 0)
88 {
90 d = c % d;
91 c = tmp;
92 }
93
94 return c;
95}
96
126template <typename IntTypeA, typename IntTypeB>
127constexpr inline auto
129{
130 static_assert(std::is_integral<IntTypeA>::value and std::is_integral<IntTypeB>::value,
131 "lcm() arguments must be integers");
132
133 static_assert(std::is_signed<IntTypeA>::value == std::is_signed<IntTypeB>::value,
134 "lcm() arguments must have the same signedness");
135
136 using CommonType = std::common_type_t<IntTypeA, IntTypeB>;
137
138 if (a == 0 && b == 0)
139 return CommonType{ 0 };
140
141 return static_cast<CommonType>(gul17::abs((a / gcd(a, b)) * b));
142}
143
145
146} // namespace gul17
147
148#endif
auto constexpr bit_set(unsigned bit) noexcept -> ReturnT
Set a bit in an integral type.
Definition bit_manip.h:124
constexpr auto lcm(IntTypeA a, IntTypeB b)
Calculate the least common multiple of two integers.
Definition gcd_lcm.h:128
constexpr auto gcd(IntTypeA a, IntTypeB b)
Calculate the greatest common divisor of two integers using the Euclidean algorithm.
Definition gcd_lcm.h:74
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:56
Definition of macros used internally by GUL.
Namespace gul17 contains all functions and classes of the General Utility Library.
Definition doxygen.h:29
Declaration of numerical utility functions.