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

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

I saw this question, and pop up this idea.

23条回答
  •  我在风中等你
    2020-12-02 08:41

    You can do better than repeated division, which takes O(lg(X) * |division|) time. Essentially you do a binary search on powers of 3. Really we will be doing a binary search on N, where 3^N = input value). Setting the Pth binary digit of N corresponds to multiplying by 3^(2^P), and values of the form 3^(2^P) can be computed by repeated squaring.

    Algorithm

    • Let the input value be X.
    • Generate a list L of repeated squared values which ends once you pass X.
    • Let your candidate value be T, initialized to 1.
    • For each E in reversed L, if T*E <= X then let T *= E.
    • Return T == X.

    Complexity:

    O(lg(lg(X)) * |multiplication|) - Generating and iterating over L takes lg(lg(X)) iterations, and multiplication is the most expensive operation in an iteration.

提交回复
热议问题