Check if a number is power of k using base changing method | Python program to check if a number can be raised to k ; loop to change base n to base = k ; Find current digit in base k ; If digit is neither 0 nor 1 ; Make sure that only one 1 is present . ; Driver code
def isPowerOfK ( n , k ) : NEW_LINE INDENT oneSeen = False NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % k NEW_LINE if ( digit > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( digit == 1 ) : NEW_LINE INDENT if ( oneSeen ) : NEW_LINE INDENT return False NEW_LINE DEDENT oneSeen = True NEW_LINE DEDENT n //= k NEW_LINE DEDENT return True NEW_LINE DEDENT n = 64 NEW_LINE k = 4 NEW_LINE if ( isPowerOfK ( n , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT