# Check if a number can be expressed as a^b in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a number n. We have to check whether we can make express it like a^b or not.

So, if the input is like 125, then the output will be True as 125 = 5^3, so a = 5 and b = 3

To solve this, we will follow these steps −

• if num is same as 1, then:
• return true
• for initialize i := 2, when i * i <= num, update (increase i by 1), do:
• val := log(num) / log(i)
• if val - integer part of val is nearly 0, then:
• return true
• return false

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include<iostream>
#include<cmath>
using namespace std;

bool solve(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 << solve(n);
}

## Input

125

## Output

1