In number theory, the integer square root (isqrt) of a non-negative integer is the non-negative integer which is the greatest integer less than or equal to the square root of ,

For example,

Introductory remark Let and be non-negative integers.

Algorithms that compute (the decimal representation of) run forever on each input which is not a perfect square.The square roots of the perfect squares (e.g., 0, 1, 4, 9, 16) are integers. In all other cases, the square roots of positive integers are irrational numbers.

Algorithms that compute do not run forever, but are nevertheless capable of computing up to any desired accuracy .

Choose any and compute .

For example (setting ):

Compare the results with

It appears that the multiplication of the input by gives an accuracy of decimal digits.It is no surprise that the repeated multiplication by is a feature in

To compute the (entire) decimal representation of , one can execute an infinite number of times, increasing by a factor at each pass.

Assume that in the next program () the procedure is already defined and — for the sake of the argument — that all variables can hold integers of unlimited magnitude.

Then will print the entire decimal representation of .The fractional part of square roots of perfect squares is rendered as .

import math # assume isqrt computation as given here

def sqrtForever(y: int): """ Print sqrt(y), without halting """ result = math.isqrt(y) print(str(result) + ".", end="") # print result, followed by a decimal point

while True: # repeat forever ... y *= 100 # theoretical example: overflow is ignored result = math.isqrt(y) print(str(result % 10), end="") # print last digit of result

The conclusion is that algorithms which compute are computationally equivalent to algorithms which compute .

Another derivation of from is given in section Continued fraction of √c based on isqrt below.

Basic algorithms The integer square root of a non-negative integer can be defined as

For example, because .

Algorithm using linear search The following Python programs are straightforward implementations.

Linear search using addition In the program above (linear search, ascending) one can replace multiplication by addition, using the equivalence

def isqrt(y: int) -> int: """ Integer square root (linear search, ascending) using addition """ L = 0 a = 1 d = 3

while a <= y: a = a + d d = d + 2 L = L + 1

return L

Algorithm using binary search Linear search sequentially checks every value until it hits the smallest where .

A speed-up is achieved by using binary search instead. def isqrt(y: int) -> int: """ Integer square root (binary search) """ L = 0 # lower bound of the square root R = y + 1 # upper bound of the square root

while (L != R - 1): M = (L + R) // 2 # midpoint to test if (M * M <= y): L = M else: R = M

return L

Numerical examples , . Using binary search the computation of converges to in iteration steps via the sequence

The computation of converges to in steps via the sequence

Linear search (ascending, starting from ) needs steps.

Algorithm using Newton's method One way of calculating and is to use Heron's method, which is a special case of Newton's method, to find a solution for the equation , giving the iterative formula

The sequence converges quadratically to as .See Heron's method.

Using only integer division For computing one can use the quotient of Euclidean division for both of the division operations. This has the advantage of only using integers for each intermediate value, thus making the use of floating point representations unnecessary.

Let and initial guess . Define the integer sequence:

Proof of convergence 1. Positivity: All terms are positive integers: for all .

2. Monotonicity: If , then ; so . Hence the sequence decreases.

If , then ; so . Hence the sequence increases or stays the same.

3. Boundedness: The sequence is bounded below by 1 and above by , so it is bounded.

4. Stabilization / Oscillation: A bounded monotone integer sequence either stabilizes or oscillates between two consecutive integers: or .

5. Integer "Fixed-point" Condition: At stabilization or oscillation: . This ensures that the sequence is either at or oscillating between the two nearest integers around .

6. Conclusion: The sequence eventually stabilizes at or oscillates between and .

Remark: is a strict fixed point unless is a perfect square. If is a perfect square, the sequence oscillates between and .

Example implementation def isqrt(n: int, x0: int = 1) -> int: """ isqrt via Newton-Heron iteration with specified initial guess. Uses 2-cycle oscillation detection.

Preconditions: n >= 0 # isqrt(0) = 0 x0 > 0, defaults to 1 # initial guess

Output: isqrt(n) """ assert n >= 0 and x0 > 0, "Invalid input"

# isqrt(0) = 0; isqrt(1) = 1 if n < 2: return n

prev2 = -1 # x_{i-2} prev1 = x0 # x_{i-1}

while True: x1 = (prev1 + n // prev1) // 2

# Case 1: converged (steady value) if x1 == prev1: return x1

# Case 2: oscillation (2-cycle) if x1 == prev2 and x1 != prev1: # We’re flipping between prev1 and prev2 # Choose the smaller one (the true integer sqrt) return min(prev1, x1)

# Move forward prev2, prev1 = prev1, x1

Numerical examples The call isqrt(2000000) converges to in 14 passes through while: . One iteration is gained by setting x0 to with the call isqrt(2000000, 1000000). Although Heron's method converges quadratically close to the solution, less than one bit precision per iteration is gained at the beginning. This means that the choice of the initial estimate is critical for the performance of the algorithm.Newton's method can be given as follows(with the initial guess set to ): def isqrt(s: int) -> int: """isqrt via Newton/Heron iteration.""" L, R = 1, s while L < R: R = L + ((R - L) // 2) L = s // R return R Computations , . The computation of consists in steps:

One sees that the performance gain of Newton's method over binary search is due to the fact that is approached simultaneously from Left and Right, whereas binary search adjusts only one side at each iteration. When a fast computation for the integer part of the binary logarithm or for the bit-length is available (like e.g. n.bit_length() in Python), one should better start at which is the least power of two bigger than . In the example of the integer square root of , , , and the resulting sequence is In this case only four iteration steps are needed. This corresponds to the call isqrt(2000000, 2048).

Digit-by-digit algorithm

The traditional pen-and-paper algorithm for computing the square root is based on working from higher digit places to lower, and as each new digit pick the largest that will still yield a square . If stopping after the one's place, the result computed will be the integer square root.

Using bitwise operations

If working in base 2, the choice of digit is simplified to that between 0 (the "small candidate") and 1 (the "large candidate"), and digit manipulations can be expressed in terms of binary shift operations. With * being multiplication, << being left shift, and >> being logical right shift, a recursive algorithm to find the integer square root of any natural number is: def isqrt_recursive(n: int) -> int: assert n >= 0, "n must be a non-negative integer" if n < 2: return n

# Recursive call: small_cand = isqrt_recursive(n >> 2) << 1 # same as 2 * isqrt(n // 4) large_cand = small_cand + 1 if large_cand * large_cand > n: return small_cand else: return large_cand Equivalent non-recursive program:The algorithm is explained in Square_root_algorithms#Binary numeral system (base 2) def isqrt_iterative(x: int) -> int: """ Guy, Martin (1985). "Fast integer square root by Mr. Woo's abacus algorithm" """ assert x >= 0, "x must be a non-negative integer"

op = x; res = 0

# note: i << 1 is 2 * i, i << 2 is 4 * i, # i >> 1 is i // 2, and i >> 2 is i // 4...

# "one" starts at the highest power of four <= x one = 1 while one <= op: one <<= 2 one >>= 2

while one != 0: dltasqr = res + one if op >= dltasqr: op -= dltasqr res += one << 1 res >>= 1 one >>= 2

return res

See for an example.

Karatsuba square root algorithm

The Karatsuba square root algorithm applies the same divide-and-conquer principle as the Karatsuba multiplication algorithm to compute integer square roots. The method was formally analyzed by Paul Zimmermann (1999). It recursively splits the input number into high and low halves, computes the square root of the higher half, and then determines the lower half algebraically.

Algorithm Paul Zimmermann (1999) gives the following algorithm.

Because only one recursive call is made per level, the total complexity remains in the number of bits. Each level performs only linear-time arithmetic on half-size numbers.

Comparison with Karatsuba multiplication Property Karatsuba multiplication Karatsuba-style square root Recursive calls per level 3 1 Recurrence Asymptotic complexity Key operation Three partial multiplications and recombination One recursive square root and algebraic correction

Use and history The Karatsuba-style square root is mainly used for arbitrary-precision arithmetic on very large integers, where it combines efficiently with and Karatsuba multiplication. It was first analyzed formally by Paul Zimmermann (1999). Earlier practical work includes Martin Guy (1985), and recursive versions appear in Donald Knuth (1998). Modern GMP and MPIR libraries implement similar recursive techniques.

Implementation in Python The Python program below implements Zimmermann’s algorithm. Given an integer , SqrtRem computes simultaneously its integer square root and the corresponding remainder . The choice of isqrt() is ad libitum. def SqrtRem(n: int, word_bits: int = 32) -> tuple[int, int]: """ Implementation based on Zimmermann's Karatsuba-style integer square root algorithm [Zimmermann, 1999]. It recursively splits the input n into "limbs" of size `word_bits` and combines partial results to compute the integer square root.

Args: n (int): Non-negative integer to compute the square root of. word_bits (int, optional): Number of bits per "limb" or chunk used when recursively splitting n. Default is 32. Each limb represents a fixed-size part of n for the algorithm.

Returns: tuple[int, int]: s = integer square root of n, r = remainder (n - s*s).

Notes: The limb size controls recursion granularity. Larger word_bits reduces recursion depth but increases the size of subproblems; smaller word_bits increases recursion depth but works on smaller chunks.

Reference: Zimmermann, P. (1999). "Karatsuba Square Root", Research report #3805, Inria. Archived: https://inria.hal.science/inria-00072854v1/file/RR-3805.pdf """ if n < 0: raise ValueError("n must be non-negative") if n == 0: return 0, 0 # trivial case

# Determine number of word-sized limbs (mimics “limb” splitting in Zimmermann) limblen = (n.bit_length() + word_bits - 1) // word_bits

# Base case: single limb — compute directly if limblen <= 1: s = isqrt(n) # any isqrt, e.g., math.isqrt or custom r = n - s*s return s, r

# --- Step 1: Split n into high and low parts --- half_limbs = limblen // 2 shift = half_limbs * word_bits hi = n >> shift # high half, corresponds to a3*b + a2 lo = n & ((1 << shift) - 1) # low half, corresponds to a1*b + a0

# --- Step 2: Recursive call on the high part --- s_high, r_high = SqrtRem(hi, word_bits) # approximate sqrt of high half

# --- Step 3: Recombine to approximate full sqrt --- quarter = shift // 2 numerator = (r_high << quarter) | (lo >> quarter) # simulate Zimmermann’s DivRem step denominator = s_high << 1 # 2*s' term

q = numerator // denominator if denominator else 0 # integer division s_candidate = (s_high << quarter) + q # recombine high and low

# --- Step 4: Verification and correction ---