Skip to content

Instantly share code, notes, and snippets.

@ziap
Last active October 26, 2023 03:09
Show Gist options
  • Save ziap/3e042b178c10d2ed58cb78c7ced271a1 to your computer and use it in GitHub Desktop.
Save ziap/3e042b178c10d2ed58cb78c7ced271a1 to your computer and use it in GitHub Desktop.
Sqrt with algorithm for integer for C++
#ifndef SQRT_HPP
#define SQRT_HPP
#include <type_traits>
template <typename T>
constexpr T sqrt(T value) {
if constexpr (std::is_integral_v<T>) {
T op = value;
T res = 0;
T one = (T)1 << ((sizeof(T) * 8 - 1) & -2);
while (one > op) one >>= 2;
while (one) {
if (op >= (res + one)) {
op -= res + one;
res = (res >> 1) + one;
} else {
res >>= 1;
}
one >>= 2;
}
return res;
} else if constexpr (std::is_same_v<T, double>) {
return __builtin_sqrt(value);
} else if constexpr (std::is_same_v<T, float>) {
return __builtin_sqrtf(value);
} else if constexpr (std::is_same_v<T, long double>) {
return __builtin_sqrtl(value);
} else {
static_assert(sizeof(T) & 0, "Argument is not a number");
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment