- Steps
- 27 -> 9 -> 3 -> 1
Check Power of 3 in Python
What you’ll learn
- Which numbers are powers of three.
- How repeated division by 3 proves the check.
- How to test one value and print range results.
Overview
Powers of three are 1, 3, 9, 27, 81... To test n, divide by 3 repeatedly while divisible; end at 1 means true.
Integer-only check
No floating math needed.
Live preview
Shows each divide-by-3 step.
Range list
From 1 to 20: 1, 3, 9.
Prerequisites
Integer division and modulo operation in Python.
- Use
whileloops and conditions. - Know
n % 3 == 0means divisible by 3.
What is a power of 3?
A power of 3 is any number equal to 3^k for k >= 0.
The sequence is 1, 3, 9, 27, 81...
Why repeated division works
Pure powers of three can keep dividing by 3 and eventually reach 1. Others stop at a non-1 value.
After division loop, n == 1 means power of three.
Quick examples
- Steps
- 15 -> 5 (stop)
- Reason
- 3^0 = 1
Live preview
Shows each division step until the value is no longer divisible by 3.
Algorithm
Goal: return true only if n can be reduced to 1 by repeated exact division by 3.
Reject n <= 0
Only positive values are valid here.
Divide while divisible
While n % 3 == 0, set n = n // 3.
Check final value
n == 1 means power of 3.
📜 Pseudocode
function is_power_of_three(n):
if n <= 0:
return false
while n mod 3 == 0:
n = n / 3
return n == 1 Check a single number
Checks whether a number is exactly 3^k.
def is_power_of_3(n: int) -> bool:
if n <= 0:
return False
while n % 3 == 0:
n //= 3
return n == 1
number = 27
if is_power_of_3(number):
print(f"{number} is a power of 3.")
else:
print(f"{number} is not a power of 3.") Powers of 3 from 1 to 20
Reuses helper function for range listing.
def is_power_of_3(n: int) -> bool:
if n <= 0:
return False
while n % 3 == 0:
n //= 3
return n == 1
start, end = 1, 20
print(f"Power of 3 in the range {start} to {end}:")
for i in range(start, end + 1):
if is_power_of_3(i):
print(i, end=" ") Notes
Integer-safe. Division loop avoids floating-point issues from logarithms.
Alternative. For bounded ranges, precompute powers of 3 and check membership.
Comparison. Power-of-2 has a bitwise shortcut; power-of-3 usually does not.
❓ FAQ
🔄 Input / output examples
Test these values in example 1.
| Input number | Typical line |
|---|---|
| 27 | 27 is a power of 3. |
| 10 | 10 is not a power of 3. |
| 1 | 1 is a power of 3. |
| 0 | 0 is not a power of 3. |
Edge cases
True
1 = 3^0.
False
Powers of 3 here are positive only.
Not always true
6 divides by 3 once to 2, so fails.
⏱️ Time and space complexity
| Approach | Time (single n) | Extra space |
|---|---|---|
| Divide-by-3 loop | O(log_3 n) | O(1) |
| Range scan [1, U] | O(U log U) | O(1) |
Summary
- Power of 3 means n = 3^k for k >= 0.
- Use repeated exact division by 3 and finish at 1.
- Reject n <= 0 in this tutorial.
Powers of three grow as 1, 3, 9, 27, 81... Repeated division by 3 is the clearest exact integer check for this pattern.
8 people found this page helpful
