units
Use physical dimensions at compile-time or run-time.
gcd.hpp
Go to the documentation of this file.
1 /// @file vnix/gcd.hpp
2 /// @brief Definition of vnix::gcd.
3 /// @copyright 2019 Thomas E. Vaughan; all rights reserved.
4 /// @license BSD Three-Clause; see LICENSE.
5 
6 #ifndef VNIX_GCD_HPP
7 #define VNIX_GCD_HPP
8 
9 /// Thomas E. Vaughan's public software.
10 namespace vnix {
11 
12 
13 /// Output-type resulting from modular division of input-types.
14 /// @tparam U One input type.
15 /// @tparam V Other input type.
16 template <typename U, typename V> using gcd_promoted = decltype(U() % V());
17 
18 
19 namespace impl {
20 
21 
22 /// Greatest common divisor of two nonnegative numbers.
23 /// @param a First nonnegative number.
24 /// @param b Second nonnegative number.
25 /// @return Greatest common divisor.
26 template <typename A, typename B>
27 constexpr gcd_promoted<A, B> basic_gcd(A a, B b) {
28  if (b == 0) { return a; }
29  return basic_gcd(b, a % b);
30 }
31 
32 
33 } // namespace impl
34 
35 
36 /// Greatest common divisor of two numbers; only absolute values are used.
37 /// @param a First number.
38 /// @param b Second number.
39 /// @return Greatest common divisor.
40 template <typename A, typename B> constexpr gcd_promoted<A, B> gcd(A a, B b) {
41  if (a < 0) { a = -a; }
42  if (b == 0) { return a; }
43  if (b < 0) { b = -b; }
44  return impl::basic_gcd(b, a % b);
45 }
46 
47 
48 } // namespace vnix
49 
50 #endif // ndef VNIX_GCD_HPP
constexpr gcd_promoted< A, B > basic_gcd(A a, B b)
Greatest common divisor of two nonnegative numbers.
Definition: gcd.hpp:27
constexpr gcd_promoted< A, B > gcd(A a, B b)
Greatest common divisor of two numbers; only absolute values are used.
Definition: gcd.hpp:40
Thomas E. Vaughan&#39;s public software.
Definition: rational.hpp:13