Created
December 1, 2011 15:46
-
-
Save davorb/1417706 to your computer and use it in GitHub Desktop.
fast square root java
This file contains 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
/** 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