
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements