So I need to sqrt a BigInteger in pre Java 9 and I found below function to do that. I do understand the code, but I don't really get why its there. So I guess I don't really get the math behind it. Like why is (n / 32 + 8) used. Why is mid calculated the way it is. etc.
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);
}