How to check if an integer is a power of 3?

前端 未结 23 1145
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 08:15

I saw this question, and pop up this idea.

23条回答
  •  不知归路
    2020-12-02 08:42

    This is a constant time method! Yes. O(1). For numbers of fixed length, say 32-bits.

    Given that we need to check if an integer n is a power of 3, let us start thinking about this problem in terms of what information is already at hand.

    1162261467 is the largest power of 3 that can fit into an Java int.
    1162261467 = 3^19 + 0

    The given n can be expressed as [(a power of 3) + (some x)]. I think it is fairly elementary to be able to prove that if x is 0(which happens iff n is a power of 3), 1162261467 % n = 0.

    The general idea is that if X is some power of 3, X can be expressed as Y/3a, where a is some integer and X < Y. It follows the exact same principle for Y < X. The Y = X case is elementary.

    So, to check if a given integer n is a power of three, check if n > 0 && 1162261467 % n == 0.

提交回复
热议问题