Integer square root
   HOME

TheInfoList



OR:

In
number theory Number theory (or arithmetic or higher arithmetic in older usage) is a branch of pure mathematics devoted primarily to the study of the integers and integer-valued functions. German mathematician Carl Friedrich Gauss (1777–1855) said, "Mat ...
, the integer square root (isqrt) of a
non-negative integer In mathematics, the natural numbers are those numbers used for counting (as in "there are ''six'' coins on the table") and ordering (as in "this is the ''third'' largest city in the country"). Numbers used for counting are called '' cardinal ...
''n'' is the non-negative integer ''m'' which is the greatest integer less than or equal to the
square root In mathematics, a square root of a number is a number such that ; in other words, a number whose ''square'' (the result of multiplying the number by itself, or  ⋅ ) is . For example, 4 and −4 are square roots of 16, because . ...
of ''n'', : \mbox( n ) = \lfloor \sqrt n \rfloor. For example, \mbox(27) = \lfloor \sqrt \rfloor = \lfloor 5.19615242270663 ... \rfloor = 5.


Introductory remark

Let y \text k be non-negative integers. Algorithms that compute (the
decimal representation A decimal representation of a non-negative real number is its expression as a sequence of symbols consisting of decimal digits traditionally written with a single separator: r = b_k b_\ldots b_0.a_1a_2\ldots Here is the decimal separator, i ...
of) \sqrt y run forever on each input y which is not a perfect square. Algorithms that compute \lfloor \sqrt y \rfloor do not run forever. They are nevertheless capable of computing \sqrt y up to any desired accuracy k. Choose any k and compute \lfloor \sqrt \rfloor. For example (setting y = 2): :\begin & k = 0: \lfloor \sqrt \rfloor = \lfloor \sqrt \rfloor = 1 \\ & k = 1: \lfloor \sqrt \rfloor = \lfloor \sqrt \rfloor = 14 \\ & k = 2: \lfloor \sqrt \rfloor = \lfloor \sqrt \rfloor = 141 \\ & k = 3: \lfloor \sqrt \rfloor = \lfloor \sqrt \rfloor = 1414 \\ & ... \\ & k = 8: \lfloor \sqrt \rfloor = \lfloor \sqrt \rfloor = 141421356 \\ & ... \\ \end Compare the results with \sqrt = 1.41421356237309504880168872420969807856967187537694 ... It appears that the multiplication of the input by 100^ gives an accuracy of k decimal digits. To compute the (entire) decimal representation of \sqrt y, one can execute \mbox( y ) an infinite number of times, increasing y by a factor 100 at each pass. Assume that in the next program (\mbox) the procedure \mbox( y ) is already defined and — for the sake of the argument — that all variables can hold integers of unlimited magnitude. Then \mbox(y) will print the entire decimal representation of \sqrt y. // Print sqrt(y), without halting void sqrtForever( unsigned int y ) The conclusion is that algorithms which compute isqrt() are computationally equivalent to algorithms which compute sqrt().see '
Methods of computing square roots Methods of computing square roots are numerical analysis algorithms for approximating the principal, or non-negative, square root (usually denoted \sqrt, \sqrt /math>, or S^) of a real number. Arithmetically, it means given S, a procedure for fi ...
'.


Basic algorithms

The integer square root of a
non-negative integer In mathematics, the natural numbers are those numbers used for counting (as in "there are ''six'' coins on the table") and ordering (as in "this is the ''third'' largest city in the country"). Numbers used for counting are called '' cardinal ...
y can be defined as :\lfloor \sqrt y \rfloor = \mu x ((x+1)^2 > y) For example, \mbox(27) = \lfloor \sqrt \rfloor = 5 because 6^2 > 27 \text 5^2 \ngtr 27.


Algorithm using linear search

The following C-programs are straightforward implementations.


Linear search ...


... using addition

In the program above (linear search, ascending) one can replace multiplication by addition, using the equivalence :(L+1)^2 = L^2 + 2L + 1 = L^2 + 1 + \sum_^L 2. // Integer square root // (linear search, ascending) using addition unsigned int isqrt( unsigned int y )


Algorithm using binary search

Linear search sequentially checks every value until it hits the smallest x where x^2 > y. A speed-up is achieved by using
binary search In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the ...
instead. The following C-program is an implementation. // Integer square root (using binary search) unsigned int isqrt( unsigned int y ) Numerical example For example, if one computes \mbox( 2000000 ) using binary search, one obtains the ,R/math> sequence :\begin & ,2000001\rightarrow ,1000000\rightarrow ,500000\rightarrow ,250000\rightarrow ,125000\rightarrow ,62500\rightarrow ,31250\rightarrow ,15625\\ & \rightarrow ,7812\rightarrow ,3906\rightarrow ,1953\rightarrow 76,1953\rightarrow 76,1464\rightarrow 220,1464\rightarrow 342,1464\rightarrow 403,1464\\ & \rightarrow 403,1433\rightarrow 403,1418\rightarrow 410,1418\rightarrow 414,1418\rightarrow 414,1416\rightarrow 414,1415\end This computation takes 21 iteration steps, whereas linear search (ascending, starting from 0) needs steps.


Algorithm using Newton's method

One way of calculating \sqrt and \mbox( n ) is to use Heron's method, which is a special case of Newton's method, to find a solution for the equation x^ - n = 0, giving the iterative formula : _ = \frac\left(x_k + \frac\right), \quad k \ge 0, \quad x_0 > 0. The
sequence In mathematics, a sequence is an enumerated collection of objects in which repetitions are allowed and order matters. Like a set, it contains members (also called ''elements'', or ''terms''). The number of elements (possibly infinite) is calle ...
\ converges quadratically to \sqrt as k\to \infty.


Stopping criterion

One can prove that c=1 is the largest possible number for which the stopping criterion :, x_ - x_, < c ensures \lfloor x_ \rfloor=\lfloor \sqrt n \rfloor in the algorithm above. In implementations which use number formats that cannot represent all rational numbers exactly (for example, floating point), a stopping constant less than one should be used to protect against roundoff errors.


Domain of computation

Although \sqrt is
irrational Irrationality is cognition, thinking, talking, or acting without inclusion of rationality. It is more specifically described as an action or opinion given through inadequate use of reason, or through emotional distress or cognitive deficiency. T ...
for many n, the sequence \ contains only
rational Rationality is the quality of being guided by or based on reasons. In this regard, a person acts rationally if they have a good reason for what they do or a belief is rational if it is based on strong evidence. This quality can apply to an abi ...
terms when x_0 is rational. Thus, with this method it is unnecessary to exit the field of rational numbers in order to calculate \mbox( n ), a fact which has some theoretical advantages.


Using only integer division

For computing \lfloor \sqrt n \rfloor for very large integers ''n'', one can use the quotient of
Euclidean division In arithmetic, Euclidean division – or division with remainder – is the process of dividing one integer (the dividend) by another (the divisor), in a way that produces an integer quotient and a natural number remainder strictly smaller than ...
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 In computing, floating-point arithmetic (FP) is arithmetic that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can b ...
representations of large numbers unnecessary. It is equivalent to using the iterative formula : _ = \left\lfloor \frac\left(x_k + \left\lfloor \frac \right\rfloor \right) \right\rfloor, \quad k \ge 0, \quad x_0 > 0, \quad x_0 \in \mathbb. By using the fact that : \left\lfloor \frac\left(x_k + \left\lfloor \frac \right\rfloor \right) \right\rfloor = \left\lfloor \frac\left(x_k + \frac \right) \right\rfloor, one can show that this will reach \lfloor \sqrt n \rfloor within a finite number of iterations. In the original version, one has _\ge \sqrt n for k \ge 1, and _> _ for _> \sqrt n. So in the integer version, one has \lfloor _\rfloor \ge \lfloor\sqrt n\rfloor and _\ge \lfloor _\rfloor > _ \ge \lfloor _\rfloor until the final solution _ is reached. For the final solution _, one has \lfloor \sqrt n\rfloor\le\lfloor _\rfloor \le \sqrt n and \lfloor_\rfloor \ge \lfloor_\rfloor , so the stopping criterion is \lfloor_\rfloor \ge \lfloor_\rfloor . However, \lfloor \sqrt n \rfloor is not necessarily a fixed point of the above iterative formula. Indeed, it can be shown that \lfloor \sqrt n \rfloor is a fixed point if and only if n + 1 is not a perfect square. If n + 1 is a perfect square, the sequence ends up in a period-two cycle between \lfloor \sqrt n \rfloor and \lfloor \sqrt n \rfloor + 1 instead of converging.


Example implementation in C

// Square root of integer unsigned int int_sqrt ( unsigned int s )


Numerical example

For example, if one computes the integer square root of 2000000 using the algorithm above, one obtains the sequence :\begin & 1000000 \rightarrow 500001 \rightarrow 250002 \rightarrow 125004 \rightarrow 62509 \rightarrow 31270 \rightarrow 15666 \rightarrow 7896 \\ & \rightarrow 4074 \rightarrow 2282 \rightarrow 1579 \rightarrow 1422 \rightarrow 1414 \rightarrow 1414 \end Totally 13 iteration steps are needed. 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. When a fast computation for the integer part of the binary logarithm or for the bit-length is available (like e.g. std::bit_width in
C++20 C20 or C-20 may refer to: Science and technology * Carbon-20 (C-20 or 20C), an isotope of carbon * C20, the smallest possible fullerene (a carbon molecule) * C20 (engineering), a mix of concrete that has a compressive strength of 20 newtons per sq ...
), one should better start at :x_0 = 2^, which is the least power of two bigger than \sqrt n. In the example of the integer square root of 2000000, \lfloor \log_2 n \rfloor=20, x_0=2^=2 048, and the resulting sequence is : 2048\rightarrow 1512\rightarrow 1417\rightarrow 1414 \rightarrow 1414. In this case only 4 iteration steps are needed.


Digit-by-digit algorithm

The traditional pen-and-paper algorithm for computing the square root \sqrt is based on working from higher digit places to lower, and as each new digit pick the largest that will still yield a square \leq n. 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 Recursion (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics ...
algorithm to find the integer square root of any
natural number In mathematics, the natural numbers are those numbers used for counting (as in "there are ''six'' coins on the table") and ordering (as in "this is the ''third'' largest city in the country"). Numbers used for counting are called ''cardinal ...
is: def integer_sqrt(n: int) -> int: assert n >= 0, "sqrt works for only non-negative inputs" if n < 2: return n # Recursive call: small_cand = integer_sqrt(n >> 2) << 1 large_cand = small_cand + 1 if large_cand * large_cand > n: return small_cand else: return large_cand # equivalently: def integer_sqrt_iter(n: int) -> int: assert n >= 0, "sqrt works for only non-negative inputs" if n < 2: return n # Find the shift amount. See also
find first set In computer software and hardware, find first set (ffs) or find first one is a bit operation that, given an unsigned machine word, designates the index or position of the least significant bit set to one in the word counting from the least signifi ...
, # shift = ceil(log2(n) * 0.5) * 2 = ceil(ffs(n) * 0.5) * 2 shift = 2 while (n >> shift) != 0: shift += 2 # Unroll the bit-setting loop. result = 0 while shift >= 0: result = result << 1 large_cand = ( result + 1 ) # Same as result ^ 1 (xor), because the last bit is always 0. if large_cand * large_cand <= n >> shift: result = large_cand shift -= 2 return result
Traditional pen-and-paper presentations of the digit-by-digit algorithm include various optimisations not present in the code above, in particular the trick of presubtracting the square of the previous digits which makes a general multiplication step unnecessary. See for an example.


In programming languages

Some programming languages dedicate an explicit operation to the integer square root calculation in addition to the general case or can be extended by libraries to this end. * (isqrt x): Common Lisp. * math.isqrt(x):
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
.


See also

*
Methods of computing square roots Methods of computing square roots are numerical analysis algorithms for approximating the principal, or non-negative, square root (usually denoted \sqrt, \sqrt /math>, or S^) of a real number. Arithmetically, it means given S, a procedure for fi ...


Notes


External links

* * * * * * {{number theoretic algorithms Number theoretic algorithms Number theory Root-finding algorithms