Power of Three - Problem
You're given an integer n, and you need to determine whether it's a power of three. In mathematical terms, you need to check if there exists some integer x such that n = 3x.
For example:
n = 27is a power of three because33 = 27n = 9is a power of three because32 = 9n = 10is not a power of three
Goal: Return true if the number is a power of three, false otherwise.
Input & Output
example_1.py — Python
$
Input:
n = 27
›
Output:
true
💡 Note:
27 = 3³, so it's a power of three
example_2.py — Python
$
Input:
n = 0
›
Output:
false
💡 Note:
0 is not a positive power of three
example_3.py — Python
$
Input:
n = -1
›
Output:
false
💡 Note:
Negative numbers cannot be powers of three
Constraints
- -231 ≤ n ≤ 231 - 1
- Follow up: Could you solve it without loops/recursion?
Visualization
Tap to expand
Understanding the Visualization
1
Generate Powers
Start with 3^0 = 1 and multiply by 3 repeatedly
2
Check Divisibility
Test if our number divides the maximum power evenly
3
Mathematical Insight
Only powers of 3 can divide other powers of 3 evenly
Key Takeaway
🎯 Key Insight: The mathematical property leverages the fact that 3 is prime, making 3¹⁹ divisible only by powers of 3, giving us an elegant O(1) solution.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code