Check if a number is power of k using base changing method | CPP 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
#include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; bool isPowerOfK ( unsigned int n , unsigned int k ) { bool oneSeen = false ; while ( n > 0 ) { int digit = n % k ; if ( digit > 1 ) return false ; if ( digit == 1 ) { if ( oneSeen ) return false ; oneSeen = true ; } n /= k ; } return true ; } int main ( ) { int n = 64 , k = 4 ; if ( isPowerOfK ( n , k ) ) cout << " Yes " ; else cout << " No " ; }