Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can make it run slightly faster by avoiding the while loops in favor of setting low to 10 ** (len(str(x)) / n) and high to low * 10. Probably better is to replace the len(str(x)) with the bitwise length and using a bit shift. Based on my tests, I estimate a 5% speedup from the first and a 25% speedup from the second. If the ints are big enough, this might matter (and the speedups may vary). Don't trust my code without testing it carefully. I did some basic testing but may have missed an edge case. Also, these speedups vary with the number chosen.</p> <p>If the actual data you're using is much bigger than what you posted here, this change may be worthwhile.</p> <pre><code>from timeit import Timer def find_invpow(x,n): """Finds the integer component of the n'th root of x, an integer such that y ** n &lt;= x &lt; (y + 1) ** n. """ high = 1 while high ** n &lt; x: high *= 2 low = high/2 while low &lt; high: mid = (low + high) // 2 if low &lt; mid and mid**n &lt; x: low = mid elif high &gt; mid and mid**n &gt; x: high = mid else: return mid return mid + 1 def find_invpowAlt(x,n): """Finds the integer component of the n'th root of x, an integer such that y ** n &lt;= x &lt; (y + 1) ** n. """ low = 10 ** (len(str(x)) / n) high = low * 10 while low &lt; high: mid = (low + high) // 2 if low &lt; mid and mid**n &lt; x: low = mid elif high &gt; mid and mid**n &gt; x: high = mid else: return mid return mid + 1 x = 237734537465873465 n = 5 tests = 10000 print "Norm", Timer('find_invpow(x,n)', 'from __main__ import find_invpow, x,n').timeit(number=tests) print "Alt", Timer('find_invpowAlt(x,n)', 'from __main__ import find_invpowAlt, x,n').timeit(number=tests) </code></pre> <p>Norm 0.626754999161</p> <p>Alt 0.566340923309</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload