Popular recipes tagged "isqrt"http://code.activestate.com/recipes/tags/isqrt/popular/2011-08-04T05:29:16-07:00ActiveState Code RecipesInteger square root function (Python)
2011-08-04T05:29:16-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577821-integer-square-root-function/
<p style="color: grey">
Python
recipe 577821
by <a href="/recipes/users/4172944/">Steven D'Aprano</a>
(<a href="/recipes/tags/integer/">integer</a>, <a href="/recipes/tags/isqrt/">isqrt</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>, <a href="/recipes/tags/maths/">maths</a>, <a href="/recipes/tags/root/">root</a>, <a href="/recipes/tags/square/">square</a>).
</p>
<p>The <em>integer square root</em> function, or isqrt, is equivalent to floor(sqrt(x)) for non-negative x. For small x, the most convenient way to calculate isqrt is by calling int(x**0.5) or int(math.sqrt(x)), but if x is a large enough integer, the sqrt calculation overflows.</p>
<p>You can calculate the isqrt without any floating point maths, using just pure integer maths, allowing the function to operate with numbers far larger than possible with floats:</p>
<pre class="prettyprint"><code>>>> n = 1234567*(10**1000)
>>> n2 = n*n
>>> math.sqrt(n2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to float
>>> isqrt(n2) == n
True
</code></pre>