My simple problem is to create a function that determines if a number N can be written as a^n
for some given n, i.e. I need to check if N^(1/n)
is a whole number. Somehow this function yields wrong results:
def is_power(N, n):
r = float(N) ** ( 1. / float(n) )
return r.is_integer()
For n=2
it works.
For n=3
and N=1,8,27 the function yields True, which is correct. But from then on False, e.g. for 4*4*4=64
or 5*5*5=125
. How can I create a working function that finds numbers that are squares/cubes/etc.?
Floating point arithmetic is not exact--see Is floating point math broken?.
So check your answer using exact-integer math. Round r
to the nearest integer then see if the power works. This Python 3 code removes some of your redundant type-casting. For Python 2, wrap the calculation of r
into an int()
typecast (which is not needed for Python 3).
def is_power(N, n):
r = round(N ** (1.0 / n))
return r**n == N