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 = 27 is a power of three because 33 = 27
  • n = 9 is a power of three because 32 = 9
  • n = 10 is 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
Powers of Three Visualization13⁰3927813⁴...11622614673¹⁹×3×3×3×3Key Insight: Mathematical PropertySince 3 is prime, 3¹⁹ has only these divisors:1, 3, 9, 27, 81, 243, ... , 3¹⁹ (all powers of 3)Algorithm: Check if 3¹⁹ % n == 0✓ If yes → n is a power of 3✗ If no → n is not a power of 3
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.
Asked in
Google 45 Amazon 38 Microsoft 25 Apple 18
78.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen