In addition to the Babylonian method (the same as Newton's method), there is another log(n) complexity algorithm, namely the bitwise algorithm, which in practice is slightly faster than the Babylonian algorithm as it uses only binary operations. Here is the Python implementation of it:
def integer_square_root_bitwise(n):
orig_n = n
result = 0
bit = 1 << (n.bit_length() // 2 * 2)
while bit > 0:
if n >= result + bit:
n -= result + bit
result = (result >> 1) + bit
else:
result >>= 1
bit >>= 2
is_square = (result * result == orig_n)
return is_square, result
However, if you are working with huge numbers (say over 100 digits), there is a faster algorithm (it is not in the Wikipedia list https://en.wikipedia.org/wiki/Methods_of_computing_square_roots, so here I refer to it as Bo's method):
For each iteration, we are trying to get the best estimation of $\Delta = x - x_k$
- find the upper limit of $\Delta_{max} = \Bigl \lfloor \frac{y-x_k^2}{2 x_k} \Bigr \rfloor$
- find the best estimation of $\Delta$ as $\Delta = \Bigl \lceil \dfrac{y - x_k^2}{2 x_k + \delta_{max}} \Bigr \rceil$
then we have a update $x_{k+1} = x_k + \Delta$
The details of the algorithm can be found at https://botian.replnotes.com/posts/fast_integer_square_root
Here is an example output of Bo's method of computing $\sqrt{5438224}$
Finding the square root of 5438224 using Bo's method
iteration x range y - x^2
0 2304 - 129808
1 2332 0 0
The square root of 5438224 is 2332
The step 0 is an initial estimation. It finds the solution in one iteration. By comparison, here is the output of the bitwise method:
Finding the square root of 5438224 using the bitwise method
iteration result bit n
1 0 4194304 5438224
2 4194304 1048576 1243920
3 2097152 262144 1243920
4 1048576 65536 1243920
5 589824 16384 129808
6 294912 4096 129808
7 147456 1024 129808
8 73728 256 129808
9 37120 64 55824
10 18624 16 18640
11 9328 4 0
12 4664 1 0
The square root of 5438224 is 2332
It takes 12 iterations for the bitwise method to complete the processing.
We have to use a bigger number to demonstrate the iterations of Bo's method. Here is the process of computing $\sqrt{2758815150486084950425754176}$
Finding the square root of 2758815150486084950425754176 using Bo's method
iteration x range y - x^2
0 48378511622144 - 418334763712162868194597440
1 52517137969970 184933324488 765369929220257803953276
2 52524424323189 505498 3676709702624455
3 52524424323224 0 0
The square root of 2758815150486084950425754176 is 52524424323224
The same number requires 47 iterations for the bitwise algorithm to complete the computation.