Check if a number is a perfect power of another number
<p>For example, 243 is a perfect power of 3 because 243=3^5.</p>

<p>I've previously been using <code>(math.log(a) / math.log(b)).is_integer()</code>, which I thought worked fine, but then I tried it with the example above and it actually returns 4.999999999999999 due to floating point arithmetic. So it's only reliable for very small numbers, less than around 100 I've found.</p>

<p>I suppose I could use a loop to do repeated multiplication... i.e. set i to 3, then 9, then 27, then 81, then 243, which equals the target, so we know it's a perfect power. If it reaches a point where it's bigger than 243 then we know it's not a perfect power. But I'm running this check within a loop as it is, so this seems like it'd be very inefficient.</p>

<p>So is there any other way of reliably checking if a number is a perfect power of another?</p>

<p>maybe something like:</p>

<pre><code>def is_perfect_power(a, b):
  while a % b == 0:
    a = a / b
  if a == 1:
    return True
  return False

print is_perfect_power(8,2)
</code></pre>

python math