Last active
October 26, 2023 03:09
-
-
Save ziap/3e042b178c10d2ed58cb78c7ced271a1 to your computer and use it in GitHub Desktop.
Sqrt with algorithm for integer for C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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