因此,我需要在Java 9之前的版本中使用BigInteger,我发现下面的函数可以做到这一点。我确实了解该代码,但是我真的不明白为什么要在那里。因此,我想我并没有真正了解其背后的数学原理。就像为什么要使用(n / 32 + 8)。为什么要计算中间值。等等
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);
}
Run Code Online (Sandbox Code Playgroud)