mirror of
https://gitlab.com/mfocko/Codeforces.git
synced 2024-11-09 21:59:06 +01:00
chore(cpp): implement isqrt
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
1bb9745299
commit
afe1859bc6
1 changed files with 22 additions and 0 deletions
|
@ -158,6 +158,28 @@ long pow(long base, long exp) {
|
||||||
return half * half * base;
|
return half * half * base;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
T isqrt(T x) {
|
||||||
|
assert(x >= 0);
|
||||||
|
|
||||||
|
auto max_shift = 8 * sizeof(T) - 1;
|
||||||
|
auto shift = (max_shift - std::countl_zero(x)) & ~1;
|
||||||
|
auto bit = 1 << shift;
|
||||||
|
|
||||||
|
T result = 0;
|
||||||
|
while (bit != 0) {
|
||||||
|
if (x >= (result + bit)) {
|
||||||
|
x -= result + bit;
|
||||||
|
result = (result >> 1) + bit;
|
||||||
|
} else {
|
||||||
|
result = (result >> 1);
|
||||||
|
}
|
||||||
|
bit = bit >> 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
template <std::int64_t MODULO = 1000000007>
|
template <std::int64_t MODULO = 1000000007>
|
||||||
struct Z {
|
struct Z {
|
||||||
Z(std::int64_t x = 0) : x(x % MODULO) {}
|
Z(std::int64_t x = 0) : x(x % MODULO) {}
|
||||||
|
|
Loading…
Reference in a new issue