Improved algorithm by using isqrt.