Advertisement
Nickpips

BigInteger sqrt

Apr 9th, 2016
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.41 KB | None | 0 0
  1. BigInteger sqrt(BigInteger n) {
  2.     BigInteger a = BigInteger.ONE;
  3.     BigInteger b = new BigInteger(n.shiftRight(5).add(new BigInteger("8")).toString());
  4.     while (b.compareTo(a) >= 0) {
  5.         BigInteger mid = new BigInteger(a.add(b).shiftRight(1).toString());
  6.         if (mid.multiply(mid).compareTo(n) > 0)
  7.             b = mid.subtract(BigInteger.ONE);
  8.         else
  9.             a = mid.add(BigInteger.ONE);
  10.     }
  11.     return a.subtract(BigInteger.ONE);
  12. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement