python - Check if a number is a perfect power of another number -


for example, 243 perfect power of 3 because 243=3^5.

i've been using (math.log(a) / math.log(b)).is_integer(), thought worked fine, tried example above , returns 4.999999999999999 due floating point arithmetic. it's reliable small numbers, less around 100 i've found.

i suppose use loop repeated multiplication... i.e. set 3, 9, 27, 81, 243, equals target, know it's perfect power. if reaches point it's bigger 243 know it's not perfect power. i'm running check within loop is, seems it'd inefficient.

so there other way of reliably checking if number perfect power of another?

try:

b ** int(round(math.log(a, b))) == 

that is, use log() (note there 2-argument form!) guess @ integer power, verify whether "that works".

note math.log() returns sensible result integer arguments large represent float. note integer ** in python exact, , uses efficient algorithm internally (doing number of multiplications proportional number of bits in exponent).

this straightforward , more efficient (in general) than, say, repeated division.

but i'm answering question asked ;-) if had other question in mind, of other answers may more appropriate.


Comments