Arene Base
Fundamental Utilities For Safety Critical C++
Loading...
Searching...
No Matches
lcm.hpp
Go to the documentation of this file.
1
// Copyright 2026, Toyota Motor Corporation
2
//
3
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5
#
ifndef
INCLUDE_GUARD_ARENE_BASE_ARENE_BASE_MATH_LCM_HPP_
6
#
define
INCLUDE_GUARD_ARENE_BASE_ARENE_BASE_MATH_LCM_HPP_
7
8
// IWYU pragma: private, include "arene/base/math.hpp"
9
// IWYU pragma: friend "(arene/base(?!/tests)|stdlib/include/stdlib_detail)/.*"
10
11
// parasoft-begin-suppress AUTOSAR-A16_2_2-a-2 "Arene Base aggregate headers permitted by A16-2-2 Permit #1"
12
13
#
include
"arene/base/constraints/constraints.hpp"
14
#
include
"arene/base/math/abs.hpp"
15
#
include
"arene/base/math/gcd.hpp"
16
#
include
"arene/base/stdlib_choice/enable_if.hpp"
17
#
include
"arene/base/stdlib_choice/is_integral.hpp"
18
19
namespace
arene
{
20
namespace
base
{
21
22
/// @brief Calculates the Least Common Multiple (LCM) of two integral values.
23
/// @tparam Integral The type of the values
24
/// @param lhs First value
25
/// @param rhs Second value
26
/// @return value that is LCM of @c lhs and @c rhs. If either @c lhs or @c rhs is @c 0, then returns @c 0. The
27
/// result is always non-negative.
28
///
29
/// The LCM is the smallest positive integer that is divisible by both input values.
30
/// It is calculated using the mathematical identity: lcm(a,b) = abs(a*b) / gcd(a,b).
31
template
<
typename
Integral
,
constraints
<
std
::
enable_if_t
<
std
::
is_integral
<
Integral
>::
value
> > =
nullptr
>
32
constexpr
auto
lcm
(
Integral
lhs
,
Integral
rhs
)
noexcept
->
Integral
{
33
if
((
lhs
==
Integral
{}) || (
rhs
==
Integral
{})) {
34
return
Integral
{};
35
}
36
37
// lcm(a,b) can be rewritten as (a / gcd(a,b)) * b to prevent possible overflow
38
return
abs
((
lhs
/
gcd
(
lhs
,
rhs
)) *
rhs
);
39
}
40
41
}
// namespace base
42
}
// namespace arene
43
44
#
endif
// INCLUDE_GUARD_ARENE_BASE_ARENE_BASE_MATH_LCM_HPP_
arene::base
Definition
array_exceptions_disabled.cpp:11
arene
Copyright 2026, Toyota Motor Corporation.
Definition
array_exceptions_disabled.cpp:10
arene
base
math
lcm.hpp
Generated by
1.13.2