ClickHouse/src/Functions/lcm.cpp

70 lines
1.6 KiB
C++
Raw Normal View History

#include <Functions/FunctionFactory.h>
#include <Functions/FunctionBinaryArithmetic.h>
#include <Functions/GCDLCMImpl.h>
2020-08-07 23:01:05 +00:00
2021-05-08 18:19:45 +00:00
#include <boost/integer/common_factor.hpp>
2021-05-07 00:00:26 +00:00
2020-08-07 23:01:05 +00:00
namespace
{
template <typename T>
constexpr T abs(T value) noexcept
{
if constexpr (std::is_signed_v<T>)
{
if (value >= 0 || value == std::numeric_limits<T>::min())
return value;
return -value;
}
else
return value;
}
}
2019-07-15 14:45:56 +00:00
namespace DB
{
2020-09-07 18:00:37 +00:00
namespace
{
struct NameLCM { static constexpr auto name = "lcm"; };
template <typename A, typename B>
struct LCMImpl : public GCDLCMImpl<A, B, LCMImpl<A, B>, NameLCM>
{
using ResultType = typename GCDLCMImpl<A, B, LCMImpl<A, B>, NameLCM>::ResultType;
static ResultType applyImpl(A a, B b)
{
using Int = typename NumberTraits::ToInteger<ResultType>::Type;
using Unsigned = make_unsigned_t<Int>;
2020-08-07 23:01:05 +00:00
/** It's tempting to use std::lcm function.
* But it has undefined behaviour on overflow.
* And assert in debug build.
* We need some well defined behaviour instead
* (example: throw an exception or overflow in implementation specific way).
*/
2021-05-08 18:46:41 +00:00
Unsigned val1 = abs<Int>(a) / boost::integer::gcd(Int(a), Int(b));
2020-08-08 02:02:36 +00:00
Unsigned val2 = abs<Int>(b);
2020-08-07 23:01:05 +00:00
/// Overflow in implementation specific way.
return ResultType(val1 * val2);
}
};
using FunctionLCM = BinaryArithmeticOverloadResolver<LCMImpl, NameLCM, false, false>;
2020-09-07 18:00:37 +00:00
}
void registerFunctionLCM(FunctionFactory & factory)
{
factory.registerFunction<FunctionLCM>();
}
}