Skip to content

Instantly share code, notes, and snippets.

@hieblmi
Forked from JochemKuijpers/BigInteger_sqrt.java
Created March 11, 2018 22:08
Show Gist options
  • Save hieblmi/deafebd08b158d1b321441b698baa5bf to your computer and use it in GitHub Desktop.
Save hieblmi/deafebd08b158d1b321441b698baa5bf to your computer and use it in GitHub Desktop.
BigInteger sqrt(BigInteger n) {
BigInteger a = BigInteger.ONE;
BigInteger b = n.shiftRight(5).add(BigInteger.valueOf(8));
while (b.compareTo(a) >= 0) {
BigInteger mid = a.add(b).shiftRight(1);
if (mid.multiply(mid).compareTo(n) > 0) {
b = mid.subtract(BigInteger.ONE);
} else {
a = mid.add(BigInteger.ONE);
}
}
return a.subtract(BigInteger.ONE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment