Dear All,
What is your favorite algorithm to compute the n-th Square of
a BigInteger, i.e.
Given: x, n
Compute: y = max { z | z^n =< x }
(I'm assuming you mean n'th root, which is what your final
line seems to imply.)
It's not something I've found a need to do, so I have no
"favorite" algorithm. For positive `x' I think I'd start
by observing that
x.bitCount()-1 <= lg(x) < x.bitCount()
hence the lg() of the desired root is between
floor((x.bitCount()-1)/n) <= lg(root) < ceil(x.bitCount()/n)
From this you can get lower and upper bounds on the root itself,
something like (just typed in free-hand)
BigInteger lo = BigInteger.ONE.shiftLeft(
Math.floor((x.bitCount()-1)/n));
BitInteger hi = BigInteger.ONE.shiftLeft(
Math.ceil(x.bitCount()/n));
.... and then do a binary search between those extrema. (Looks like
they'd differ by a factor of two usually, maybe a factor of four
occasionally -- but I might be wrong about that.)
Simplifications might be possible if `n' is known to be an
integer.
For negative `x' and odd integer `n' you could find the bounds
for -x, negate and interchange them, and then do the same binary
search.
For negative `x' and `n' even or non-integer, I think you're
out of luck.