Check if a number is power of k using base changing methods in C++

C++Server Side ProgrammingProgramming

Here we will see a program, if one number is given, another value k is also given, we have to check whether the number is power of k or not. But we have to perform the base changing method to solve this problem. Suppose a number is 27, and k = 3. Then by base changing method, the 27 will be 10003. Here after changing the base if there is only one occurrence of digit 1, and others are 0, then the number is power of k.

To solve this problem, we will follow these steps.

Steps 

  • define flag := false
  • while number > 0, repeat steps 3 to 6
  • find digit := number mod k
  • if the digit > 1, then return false
  • otherwise when digit is 1, then if the flag is True, return false, otherwise flag := true.
  • set number := number / k.
  • return true

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
bool isPowerOfK(int num, int k) {
   bool flag = false;
   while (num > 0) {
      int digit = num % k; //get current digit in base k
      if (digit > 1) //if the digit is not 0 or 1, then it is not power of k
      return false;
      if (digit == 1) {
         if (flag)
            return false;
         flag = true;
      }
      num /= k;
   }
   return true;
}
int main() {
   int number = 27, K = 3;
   if(isPowerOfK(number, K)){
      cout << number << " is power of " << K;
   } else {
      cout << number << " is not power of " << K;
   }
}

Output

27 is power of 3
raja
Published on 22-Oct-2019 10:05:44
Advertisements