Power of Three

Easy · Math & Geometry · Explanation and code example

Divisibility by the Largest 32-Bit Power

How it works

The largest power of three within signed 32-bit range is 3^19. Its only positive divisors are powers of three. A positive input is therefore a power of three exactly when it divides this constant.

Steps

  1. Reject nonpositive values.
  2. Compute 3^19 modulo n.
  3. Accept when the remainder is zero.

Complexity

  • Time: O(1) for the specified 32-bit bound.
  • Space: O(1).

Things to watch for

  • This constant depends on the integer range.
  • One counts as 3^0.
  • Avoid logarithm rounding errors by testing integer divisibility.

Python code example

class Solution:
  def isPowerOfThree(self, n: int) -> bool:
    return n > 0 and 3**19 % n == 0

C++ code example

class Solution {
 public:
  bool isPowerOfThree(int n) {
    return n > 0 && static_cast<int>(pow(3, 19)) % n == 0;
  }
};
Source and license

Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations