Latest recipes tagged "complex"http://code.activestate.com/recipes/tags/complex/new/2015-03-05T15:59:30-08:00ActiveState Code RecipesSimple way to find number of perfect square numbers in a range. (Python)
2015-03-05T15:59:30-08:00alexander bakerhttp://code.activestate.com/recipes/users/4166679/http://code.activestate.com/recipes/579031-simple-way-to-find-number-of-perfect-square-number/
<p style="color: grey">
Python
recipe 579031
by <a href="/recipes/users/4166679/">alexander baker</a>
(<a href="/recipes/tags/complex/">complex</a>, <a href="/recipes/tags/fun/">fun</a>, <a href="/recipes/tags/interview/">interview</a>, <a href="/recipes/tags/maths/">maths</a>, <a href="/recipes/tags/range/">range</a>).
</p>
<p>The strategy here is not to iterate through the set of possible integer values and check for is_perfect_square()
each time but to translate the upper and lower values to either complex or real space of square numbers.</p>
<pre class="prettyprint"><code> # O(n) complexity
len([x for x in range(0, 100) if x!= 0 and float(math.sqrt(x)).is_integer()])
so if a and b positive then we count the number of integer values between upper and lower sqrt() values
if either a or b are negative then we need to use the complex number space for the sqrt() results. In this case
we are still counting integer values either along the imaginary or real axis, the result is then a simple sum
if both a and b are negative we need to make sure that when walking down the same imaginary axis we dont count
the same inteters twice, in this case we can take the min(a,b) to get max distinct set of integer values.
</code></pre>