
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check if a number is power of k using base changing methods in C++
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
#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
- Related Articles
- Check if a number is a power of another number in C++
- Check if a number is power of 8 or not in C++
- How to check if a number is a power of 2 in C#?
- Check if a number is in given base or not in C++
- Check if given number is a power of d where d is a power of 2 in Python
- Check if a number can be expressed as power in C++
- Check if a number N starts with 1 in b-base in C++
- Check if any permutation of N equals any power of K in Python
- Check if a number is multiple of 5 without using / and % operators in C++
- Check if a number is Palindrome in C++
- Check if a number is Bleak in C++
- Find power of a number using recursion in C#
- C Program to check if a number belongs to a particular base or not
- Check if a given number can be represented in given a no. of digits in any base in C++
- Check if a given number is Pronic in C++

Advertisements