Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if a number can be expressed as a^b in Python
Sometimes we need to check if a number can be expressed as a power of another number, i.e., whether we can write it as a^b where both a and b are positive integers.
So, if the input is like 125, then the output will be True as 125 = 5^3, so a = 5 and b = 3.
Algorithm
To solve this, we will follow these steps ?
- If num is same as 1, then return True (since 1 = 1^1)
- For each potential base i from 2 to ?num:
- Calculate val = log(num) / log(i)
- If val is very close to an integer, then return True
- If no valid base found, return False
Python Implementation
import math
def can_express_as_power(num):
if num == 1:
return True
for i in range(2, int(math.sqrt(num)) + 1):
val = math.log(num) / math.log(i)
if abs(val - round(val)) < 1e-9:
return True
return False
# Test with example
n = 125
result = can_express_as_power(n)
print(f"Can {n} be expressed as a^b? {result}")
# Test with more examples
test_cases = [1, 8, 16, 25, 32, 100, 123]
for num in test_cases:
print(f"{num}: {can_express_as_power(num)}")
Can 125 be expressed as a^b? True 1: True 8: True 16: True 25: True 32: True 100: True 123: False
How It Works
The algorithm uses logarithms to check if a number can be expressed as a power. For a number num = a^b, taking logarithms gives us log(num) = b * log(a), so b = log(num) / log(a).
If b is an integer, then num can be expressed as a^b. We check this by seeing if the calculated value is very close to its rounded integer value.
Alternative Approach Using Integer Operations
def can_express_as_power_integer(num):
if num == 1:
return True
for base in range(2, int(num**0.5) + 1):
power = base
exponent = 1
while power < num:
power *= base
exponent += 1
if power == num:
return True
return False
# Test the integer approach
test_numbers = [125, 128, 81, 100, 123]
for num in test_numbers:
result = can_express_as_power_integer(num)
print(f"{num}: {result}")
125: True 128: True 81: True 100: True 123: False
Comparison
| Method | Time Complexity | Accuracy | Best For |
|---|---|---|---|
| Logarithm-based | O(?n) | High (with precision handling) | Quick mathematical solution |
| Integer operations | O(?n * log n) | Perfect | Avoiding floating-point errors |
Conclusion
Both approaches effectively determine if a number can be expressed as a^b. The logarithm method is more mathematically elegant, while the integer approach avoids floating-point precision issues completely.
