Check if a number can be expressed as a^b in C++



Here we will check whether we can represent a number like ab or not. Suppose a number 125 is present. This can be represented as 53. Another number 91 cannot be represented as power of some integer value.

Algorithm

isRepresentPower(num): Begin    if num = 1, then return true    for i := 2, i2 <= num, increase i by 1, do       val := log(a)/log(i)       if val – int(val) < 0.0000000001, then return true    done    return false End

Example

 Live Demo

#include<iostream> #include<cmath> using namespace std; bool isRepresentPower(int num) {    if (num == 1)    return true;    for (int i = 2; i * i <= num; i++) {       double val = log(num) / log(i);    if ((val - (int)val) < 0.00000001)       return true;    }    return false; } int main() {    int n = 125;    cout << (isRepresentPower(n) ? "Can be represented" : "Cannot be represented"); }

Output

Can be represented
Updated on: 2019-09-27T08:29:51+05:30

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements