Check if a given number N is a power of k I am trying to solve a problem to check whether a given number N is a power of k.

Example:


Input 9, 3  > True //  3**2 = 9
Input 10, 2  > False
Input 4096, 16  > True // 16**3 = 4096


I want to know if there is a better solution for this problem.

def check_Power(N,k):
    if N &lt;= 0 or k &lt;=0:
        print "not a valid input"
    else:
        for i in range (1,20):
            x = k**i
            if x == N :
                print " True "
                print k, "power ", i , "is", N
                break
            elif x&gt; N:
                print "false"
                break

check_Power(244140625,5)
check_Power(4096, 16)
check_Power(0, 16)
check_Power(1,1)
I'd follow Ludisposed's answer.

Except, there's a simple way to do this. Use logarithms.
Since the equation is \$N = k^a\$ you can change it to \$a = \log_k N\$.
And so if \$a\$ is an integer, then you know that \$N\$ is a power of \$k\$.

import math

def check_power(N, k):
    return math.log(N, k).is_integer()


Since the above can error, and if there's an error it's definately not a power, then you can use:

def check_power(N, k):
    try:
        return math.log(N, k).is_integer()
    except Exception:
        return False




This has the some problems with floating point precision, so your can round the number to the closest integer, as you want to know if the \$a\$ is an integer. And so you can sub it back into the original equation to ensure that the numbers are right.

def check_power(N, k):
    return N == k**round(math.log(N, k))


Or if you're on Python 2:

def check_power(N, k):
    return N == k**int(round(math.log(N, k)))




This has a problem with some inputs, such as when \$N\$ and \$k\$ are \$0\$ or \$1\$. And so we can handle these special cases.

def check_power(N, k):
    if N == k:
        return True
    return N == k**round(math.log(N, k))




And so merging all the above, we can use the following:

def check_power(N, k):
    if N == k:
        return True
    try:
        return N == k**int(round(math.log(N, k)))
    except Exception:
        return False