Created
December 19, 2012 21:51
-
-
Save syzdek/4340863 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
intmax_t sqroot_imax(intmax_t n, int round) | |
{ | |
intmax_t op = n; | |
intmax_t res = 0; | |
intmax_t one = 1uL << ((sizeof(intmax_t)*8)-2); | |
// "one" starts at the highest power of four <= than the argument. | |
while (one > op) | |
one >>= 2; | |
while (one != 0) | |
{ | |
if (op >= res + one) | |
{ | |
op = op - (res + one); | |
res = res + 2 * one; | |
}; | |
res >>= 1; | |
one >>= 2; | |
}; | |
// Do arithmetic rounding to nearest integer | |
if ((round)) | |
if (op > res) | |
res++; | |
return(res); | |
} | |
uintmax_t sqroot_uimax(uintmax_t n, int round) | |
{ | |
uintmax_t op = n; | |
uintmax_t res = 0; | |
uintmax_t one = 1uL << ((sizeof(uintmax_t)*8)-2); | |
// "one" starts at the highest power of four <= than the argument. | |
while (one > op) | |
one >>= 2; | |
while (one != 0) | |
{ | |
if (op >= res + one) | |
{ | |
op = op - (res + one); | |
res = res + 2 * one; | |
}; | |
res >>= 1; | |
one >>= 2; | |
}; | |
// Do arithmetic rounding to nearest integer | |
if ((round)) | |
if (op > res) | |
res++; | |
return(res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment