Skip to content

Instantly share code, notes, and snippets.

@davorb
Created December 1, 2011 15:46
Show Gist options
  • Save davorb/1417706 to your computer and use it in GitHub Desktop.
Save davorb/1417706 to your computer and use it in GitHub Desktop.
fast square root java
/** Calculate the square root of a BigInteger in logarithmic time */
public BigInteger squareRoot(BigInteger x) {
BigInteger right = x, left = BigInteger.ZERO, mid;
while(right.subtract(left).compareTo(BigInteger.ONE) > 0) {
mid = (right.add(left)).shiftRight(1);
if(mid.multiply(mid).compareTo(x) > 0)
right = mid;
else
left = mid;
}
return left;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment