ClickHouse/src/Functions/gcd.cpp

53 lines
1.5 KiB
C++
Raw Normal View History

#include <Functions/FunctionFactory.h>
#include <Functions/FunctionBinaryArithmetic.h>
2019-07-15 14:45:56 +00:00
#include <numeric>
namespace DB
{
namespace ErrorCodes
{
extern const int NOT_IMPLEMENTED;
}
2020-09-07 18:00:37 +00:00
namespace
{
template <typename A, typename B>
struct GCDImpl
{
using ResultType = typename NumberTraits::ResultOfAdditionMultiplication<A, B>::Type;
static const constexpr bool allow_fixed_string = false;
template <typename Result = ResultType>
static inline Result apply([[maybe_unused]] A a, [[maybe_unused]] B b)
{
if constexpr (is_big_int_v<A> || is_big_int_v<B> || is_big_int_v<Result>)
throw Exception("GCD is not implemented for big integers", ErrorCodes::NOT_IMPLEMENTED);
else
{
throwIfDivisionLeadsToFPE(typename NumberTraits::ToInteger<A>::Type(a), typename NumberTraits::ToInteger<B>::Type(b));
throwIfDivisionLeadsToFPE(typename NumberTraits::ToInteger<B>::Type(b), typename NumberTraits::ToInteger<A>::Type(a));
return std::gcd(
typename NumberTraits::ToInteger<Result>::Type(a),
typename NumberTraits::ToInteger<Result>::Type(b));
}
}
#if USE_EMBEDDED_COMPILER
static constexpr bool compilable = false; /// exceptions (and a non-trivial algorithm)
#endif
};
struct NameGCD { static constexpr auto name = "gcd"; };
2020-09-05 14:12:47 +00:00
using FunctionGCD = BinaryArithmeticOverloadResolver<GCDImpl, NameGCD, false>;
2020-09-07 18:00:37 +00:00
}
void registerFunctionGCD(FunctionFactory & factory)
{
factory.registerFunction<FunctionGCD>();
}
}