Determine if a number n is a power

96 Views Asked by At

What would be an efficient algorithm to determine if $n \in \mathbb{N}$ can be written as $n = a^b$ for some $a,b \in \mathbb{N}, b>1$?

So far, I've tried:

def ispower(n):
    if n<=3:
        return False
    LIM = math.floor(math.log2(n))
    for b in range(2,LIM+1):
        a = math.pow(n, 1/b)
        a_floor = math.floor(a)
        print(a,a_floor)
        if a == a_floor:
            return True
    return False

That is, checking if the $b-th$ roots are integer, for $b$ from 2 to $LIM$, where $LIM$ stands for the ultimate limit of n being a power of 2.

Thanks for your comments.

2

There are 2 best solutions below

1
On

Since $n = n^1$, every number can be written in the required form. Thus an efficient algorithm is to always answer yes.

3
On

If you restrict $b\geq 2$, then the most efficient way is probably simply testing each root $b = 2, 3, \ldots, \lfloor\log_2 n\rfloor$. This is of runtime $O(\log n)$ and can be implemented using the gmpy2 module efficiently:

import gmpy2

p = 197
e = 989
n = p ** e

b = 2
while 2 ** b <= n:
    root, exact = gmpy2.iroot(n, b)
    if exact:
        print(f"n is a {b}-th power")
        break
    b += 1
else:
    print(f"n is not a perfect power.")
```