Skip to content

Commit 142b506

Browse files
committed
Add LCM impl
1 parent 769f7c9 commit 142b506

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

include/boost/int128/numeric.hpp

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,12 +281,32 @@ constexpr uint128_t gcd(uint128_t a, uint128_t b) noexcept
281281
return a << shift;
282282
}
283283

284-
constexpr int128_t gcd(int128_t a, int128_t b) noexcept
284+
constexpr int128_t gcd(const int128_t a, const int128_t b) noexcept
285285
{
286286
const auto res {static_cast<int128_t>(gcd(static_cast<uint128_t>(abs(a)), static_cast<uint128_t>(abs(b))))};
287287
return a < 0 != b < 0 ? -res : res;
288288
}
289289

290+
constexpr uint128_t lcm(const uint128_t a, const uint128_t b) noexcept
291+
{
292+
if (a == 0U || b == 0U)
293+
{
294+
return static_cast<uint128_t>(0);
295+
}
296+
297+
// Calculate GCD first
298+
const auto g {gcd(a, b)};
299+
300+
// Compute LCM avoiding overflow: (a/gcd) * b
301+
return (a / g) * b;
302+
}
303+
304+
constexpr int128_t lcm(const int128_t a, const int128_t b) noexcept
305+
{
306+
const auto res {static_cast<int128_t>(lcm(static_cast<uint128_t>(abs(a)), static_cast<uint128_t>(abs(b))))};
307+
return a < 0 != b < 0 ? -res : res;
308+
}
309+
290310
} // namespace int128
291311
} // namespace boost
292312

0 commit comments

Comments
 (0)