
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if a number can be expressed as a^b in Python
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
#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
- Related Articles
- Check if a number can be expressed as a^b in C++
- Check if a number can be expressed as power in C++
- Check if a prime number can be expressed as sum of two Prime Numbers in Python
- Check if a number can be expressed as a sum of consecutive numbers in C++
- Check if a number can be expressed as sum two abundant numbers in C++
- Check if a number can be expressed as 2^x + 2^y in C++
- Check if an integer can be expressed as a sum of two semi-primes in Python
- Check if a number can be expressed as x^y (x raised to power y) in C++
- C++ Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
- Java Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
- Haskell Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
- Swift program to check whether a number can be expressed as sum of two prime numbers
- Can a rational number be expressed a fraction?
- Check if N can be represented as sum of integers chosen from set {A, B} in Python
- Check if a number can be represented as a sum of 2 triangular numbers in C++

Advertisements