Computing the integer square root of large numbers

Computing the integer square root of large numbers Техника

A simple approach is to compute the floating point square root and truncate the result to an integer. In Swift that would be

As observed in
Computing the square root of a 64-bit integer,
this can produce wrong results for large numbers, because an IEEE 64-bit floating point
number with its 53 bit significand cannot represent large integers exactly.
Here is an example:

let n = 9223371982334239233
let r = isqrt_simple(n)

print(r) // 3037000491
print(r * r <= n) // false

The code worked correctly in all my tests. Here are some tests which all succeed

These tests fail if isqrt_simple() is used instead.

All feedback is welcome, in particular suggestions how to improve the performance.

Using the notation of the $a$ and $b$ is only necessary when programming.

You have correctly identified that the algorithm gives a sequence of values, which I will call (as you did) the $x_m$.

Let’s consider these in turn.

Considering this in two parts, we have first:

$x_m^2 le n$

$x_m le sqrt n$

$n<x_m^2 + 2 x_m$

Completing the square,

$n+1<x_m^2 + 2 x_m+1$

$n+1<(x_m + 1)^2$

$sqrt n — 1 <x_m le sqrt n$

So if the sequence converges to a value, then this will be the largest integer less than or equal to the square root of $n$.

It could be, however, that the values oscillate without converging. What about those situations?

$n — x_m^2 ge 0$

This means that an increase in the values of the sequence only happens if the value in the sequence is less than or equal to the square root. There cannot be an infinite run of increases because eventually the value will become greater than the square root. Therefore there must eventually be a decrease in the values of the sequence.

For the hell of micro-benchmarking without the likes of Java Microbenchmarking Harness or jmicrobench(no idea whether this is official) (or that most visible one for those who don’t have issues with empires), I tinkered around picking up ideas from rolfl and chillworld

In my environment, warmup of the empty/non-method made a ratio in execution time of about 100:1.

In number theory, the integer square root (isqrt) of a positive integer n is the positive integer m which is the greatest integer less than or equal to the square root of n,

For example, because and .

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 .

ensures
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 is irrational for many , the sequence contains only rational terms when is rational. Thus, with this method it is unnecessary to exit the field of rational numbers in order to calculate , a fact which has some theoretical advantages.

Using only integer division

For computing for very large integers n, 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 of large numbers unnecessary. It is equivalent to using the iterative formula

By using the fact that

one can show that this will reach within a finite number of iterations.

In the original version, one has for , and for .
So in the integer version, one has and
until the final solution is reached.
For the final solution , one has and ,
so the stopping criterion is .

However, is not necessarily a fixed point of the above iterative formula. Indeed, it can be shown that is a fixed point if and only if is not a perfect square. If is a perfect square, the sequence ends up in a period-two cycle between and instead of converging.

Example implementation in C

// Square root of integer

// Initial estimate
// Avoid overflow when s is the maximum representable value

// Sanity check

// This also checks for cycle

For example, if one computes the integer square root of 2 000 000 using the algorithm above, one obtains the sequence 1 000 000, 500 001, 250 002, 125 004, 62 509, 31 270, 15 666, 7 896, 4 074, 2 282, 1 579, 1 422, 1 414, 1 414. 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.

Дополнительно:  Startup repair offline что это как исправить -

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), one should better start at

which is the least power of two bigger than . In the example of the integer square root of 2 000 000, , , and the resulting sequence is 2 048, 1 512, 1 417, 1 414, 1 414. In this case only 4 iteration steps are needed.

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

«sqrt works for only non-negative inputs»

# Recursive call:

«sqrt works for only non-negative inputs»

# shift = ceil(log2(n) * 0.5) * 2 = ceil(ffs(n) * 0.5) * 2

# Unroll the bit-setting loop.

# Same as result ^ 1 (xor), because the last bit is always 0.

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 Methods of computing square roots § Woo abacus 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.

This article page is a stub, please help by expanding it.

This article is under construction.Please do not rely on any information it contains.

The square root of a number is the number that multiplied by itself gives . For example, the square root of 44100 is 210, since 210 × 210 = 44100. Actually, positive numbers have two square roots, one positive, one negative; e.g., –210 × –210 = 44100. The square root of a negative number is an imaginary number.

Theorem SQRT1. The square root of a positive integer is either a positive integer or an irrational number, but never a non-integral rational number.

Proof. Take the set of all positive integers and square all its members, label the resulting set . Clearly is the set of all positive integers that have integer square roots. Obviously, these integer square roots are rational numbers, as they can be expressed as , where .

Since , we can write . Multiply by to get . This means that is divisible by , and therefore (the value of is not necessary for this proof). So, and thus . Dividing both sides by we obtain . This means that is also divisible by . But we established that is also divisible by , contradicting the assertion that and are coprime, and therefore is not a rational number. ¿¿¿IS THERE A HOLE IN THIS PROOF REGARDING COMPOSITE NUMBERS???

In summary, if , then , but if not, then as specified by the theorem. □

Corollary. Much of the foregoing can be said for negative numbers with only small adjustments. For convenience, let’s say that the function returns a real value, that is to say, , not . Then, if , either or .

This proof is essentially a generalization of proofs for the square roots of specific integers. Perhaps it would be more elegant to first prove the fundamental theorem of algebra and then derive not only this result but also the similar results for cubes, biquadrates, etc.

However it is proven, this result can be used to prove the irrationality of some other numbers involving square roots quite easily. For example:

Theorem SQRT23. The number is irrational.

See A135611 for the decimal expansion of , and A089078 for the continued fraction expansion.

Theorem SQRT2.25. The square of rational number that is not an integer is another rational number that is not an integer either.

For example, .

Corollary. The square root of an integer may be an integer or it may be an irrational number, but it may not be a non-integral rational number, as that would obviously contradict what we have just proven.

The converse is not always true: the square root of a rational number that is not an integer may be an irrational number. This is the case with the reciprocals of most integers, e.g., , which is clearly irrational.

Square roots of some small integers

* With a different offset.

A note on square roots of positive integers: we can write where is squarefree. Then is given by A000188(n), which we can call the «inner square root» of , while is given by A007913(n), and is the «squarefree kernel» of , given by A007947(n); , the «outer square root» of n, is given by A019554(n). For example, .

Дополнительно:  Не работает тачпад на ноутбуке, 11 причин почему | Блог Comfy

Square roots of some important constants

As before, these are given to 20 decimal places, truncated.

The square root of –1 is the imaginary unit , and the square root of the imaginary unit is .

Hello, in this video, we will explore how to simplify square roots and find perfect squares.

Think you’ve got it? The root symbol is the radical. The index is 4 because it’s the number in the bent arm of the radical. And the radicand is the number under the radical symbol, so in this case, 200.

4 – index

200 – radicand

What are the square roots of 36, 81, and 144? Pause the video and try these on your own. When you’re finished, we’ll look over them together.

We get these nice, pretty numbers because we are taking the square roots of perfect squares. But what if we aren’t given a perfect square? Well, then we will have to simplify the square root.

Simplifying Square Roots

When simplifying a square root, we will get all the perfect squares out from under the radical and whatever is remaining from the factors of the radicand stays under the radical. Let’s look at an example.

There are no more perfect squares to take out, so we simply multiply these numbers together to get our new radicand.

Now I want you to try one. Simplify the square root of 96: 96. Pause the video here and simplify. When you’re done, we’ll take a look at it together.

Think you’ve got it? First, we need to find the factors of 96.

I hope this video on square roots and perfect squares was helpful. Thanks for watching, and happy studying!

Frequently Asked Questions

Not all numbers will have whole number square roots. For example, 1 has a square root because 1 can be expressed as the product of two equal integers, 1x1. 4 has a whole number square root because it can be expressed as the product of 2x2. However, notice how 2 and 3 will not have whole number square roots. 2 cannot be expressed as an integer multiplied by itself. Similarly, 3 cannot be expressed as an integer multiplied by itself.

Numbers with integer square roots are called perfect squares. For example, 64 is a number with an integer square root. 64 is the product of (8 imes8). When a number can be created by multiplying an integer by itself, it is called a perfect square. Examples of numbers with integer square roots are 1, 4, 9, 16, and 25. All of these numbers have integer square roots. 25 is a perfect square which is the product of (5 imes5). This means that 5 is the square root of 25.

Not all numbers will have integer square roots. For example, 5 does not have an integer square root. No integer times itself has a product of 5. We can get close: (1 imes=1), (2 imes2=4), and (3 imes3=9), but 5 is not a perfect square, so it does not have an integer square root.

There are only ten perfect squares from 1 to 100. 1, 4, 9, 16, 25, 36, 49, 64, 81, and 100. These perfect squares are the result of multiplying a number by itself. For example, 1 is a perfect square because (1 imes1=1). 4 is a perfect square because (2 imes2=4). 9 is a perfect square because (3 imes3=9). Not all numbers are perfect squares. It can be helpful to think of perfect squares as actual squares with a length and a width. For example, 100 is a perfect square built from side lengths of 10 and 10. (10 imes10=100), therefore 100 is a perfect square.

Computing the integer square root of large numbers

Numbers that are considered perfect squares are the result of multiplying an integer by itself. For example, 25 is a perfect square because it is the product of (5 imes5). A number multiplied by itself creates a perfect square.

We cannot create a perfect square by multiplying something like (11.5 imes11.5) because it is not the product of two equal integers. The square roots of perfect squares need to be integers.

Practice Questions

Which set of numbers contains all perfect squares?

33, 99, 55, 66

36, 9, 25, 100

81, 36, 25, 41

The correct answer is 36, 9, 25, 100. Thirty-six is a perfect square composed of (6×6), nine is a perfect square composed of (3×3), twenty-five is a perfect square composed of (5×5), and one hundred is a perfect square composed of (10×10).

Which pair shows a correct match between the perfect square and its whole number square root?

What is the square root of 49?

The correct answer is 7. The square root of 49 is 7, because (7×7=49). This also means that 49 is a perfect square.

Which value is NOT a perfect square?

The correct answer is 99. Because there is no whole number that can be multiplied by itself to equal 99, it is not a perfect square. Eighty-one is a perfect square composed of (9×9), one hundred is a perfect square composed of (10×10), and sixty-four is a perfect square composed of (8×8).

Дополнительно:  Техподдержка | Tantos

Which pair shows an incorrect match between the perfect square and its whole number square root?

Return to Pre-Algebra Videos

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

Let   and   be non-negative integers.

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

Choose any   and compute  .

For example (setting  ):

Compare the results with

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.

// Print sqrt(y), without halting

// theoretical example: overflow is ignored

// print last digit of result

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

For example,   because  .

// Integer square root
// (using linear search, ascending)

// initial underestimate, L <= isqrt(y)

// Integer square root
// (using linear search, descending)

// initial overestimate, isqrt(y) <= R

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

// Integer square root
// (linear search, ascending) using addition

// (a + 1) ^ 2

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

// Integer square root (using binary search)

For example, if one computes   using binary search, one obtains the   sequence

This computation takes 21 iteration steps, whereas linear search (ascending, starting from  ) needs steps.

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  .

ensures  
in the algorithm above.

Although   is irrational for many  , the sequence   contains only rational terms when   is rational. Thus, with this method it is unnecessary to exit the field of rational numbers in order to calculate  , a fact which has some theoretical advantages.

For computing   for very large integers n, 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 of large numbers unnecessary. It is equivalent to using the iterative formula

one can show that this will reach   within a finite number of iterations.

In the original version, one has   for  , and   for  .
So in the integer version, one has   and  
until the final solution   is reached.
For the final solution  , one has   and  ,
so the stopping criterion is  .

However,   is not necessarily a fixed point of the above iterative formula. Indeed, it can be shown that   is a fixed point if and only if   is not a perfect square. If   is a perfect square, the sequence ends up in a period-two cycle between   and   instead of converging.

// Square root of integer

// Zero yields zero
// One yields one

// Initial estimate (must be too high)

// Bound check

For example, if one computes the integer square root of   using the algorithm above, one obtains the sequence

In total 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.

which is the least power of two bigger than  . In the example of the integer square root of  ,  ,  , and the resulting sequence is

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.

  • LispWorks Ltd 1996.
  • Python Software Foundation 2001.
Оцените статью
Master Hi-technology