Skip to main content

How to check if a number is a power of another number in Python

How to check if a number is a power of another number in Python.

Here's a detailed step-by-step tutorial on how to check if a number is a power of another number in Python.

Step 1: Understanding the Problem

To solve this problem, we need to check if a given number num is a power of another number base. In other words, we need to determine if there exists an integer power such that base^power = num.

Step 2: Approach

To check if a number is a power of another number, we can use a simple iterative approach. We'll repeatedly divide the given number num by base until num becomes 1 or less. If num becomes exactly 1 at any point, it means that num is a power of base.

Step 3: Writing the Code

Now, let's write the code to implement this approach.

def is_power_of(num, base):
# Special case: if num is 1, it is always a power of any base
if num == 1:
return True

# Start dividing num by base
while num > 1:
if num % base != 0:
# If num is not divisible by base, it is not a power of base
return False
num = num / base

# If num becomes exactly 1, it is a power of base
return num == 1

Step 4: Testing the Code

Let's test the code with some examples to verify its correctness.

# Example 1
print(is_power_of(16, 2)) # Output: True
# Explanation: 2^4 = 16

# Example 2
print(is_power_of(81, 3)) # Output: True
# Explanation: 3^4 = 81

# Example 3
print(is_power_of(27, 4)) # Output: False
# Explanation: No power of 4 equals 27

# Example 4
print(is_power_of(10, 2)) # Output: False
# Explanation: No power of 2 equals 10

Step 5: Complexity Analysis

The time complexity of the is_power_of function is O(log(num)) because we repeatedly divide num by base until num becomes 1 or less.

Conclusion

In this tutorial, we learned how to check if a number is a power of another number in Python using an iterative approach. We implemented the code and tested it with examples to verify its correctness.