Skip to content

Instantly share code, notes, and snippets.

@syzdek
Created December 19, 2012 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syzdek/4340863 to your computer and use it in GitHub Desktop.
Save syzdek/4340863 to your computer and use it in GitHub Desktop.
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