# Math 1-liner, no log, with explanation

• ``````def isPowerOfThree(self, n):
return n > 0 == 3**19 % n
``````

The positive divisors of 319 are exactly the powers of 3 from 30 to 319. That's all powers of 3 in the possible range here (signed 32-bit integer). So just check whether the number is positive and whether it divides 319.

Got that a while back from this Stack Overflow answer (go upvote it :-).

Edit: Kudos to andrei3 for posting another version here first.

• Okay, this seems to be more interesting than before :)

But how could be find the maximum power if it is an arbitrary number rather than 3? That said, this problem still lacks meaning for software engineers in my opinion.

Java:

``````public boolean isPowerOfThree(int n) {
return n > 0 && Math.pow(3,19) % n==0;
}``````

• may use (int) (Math.log(Integer.MAX_VALUE) / Math.log(3)) instead of 19

• @liu31, I think you are right~

• It is asked by google interviewer anyway. So think of it as a brainteaser if you like.
It shows software engineer that one need to be open minded.

• Can we use Math.pow(3,32) and type long cast for n in Java? Thus in this way we are sure pow(3,32) < pow(2,64) and we don't need to calculate 19.

• I agree, I just see it as a nice little trick. Doesn't even generalize to all bases, only works for primes (for example you can't use it to check powers of 6).

• @dietpepsi, I agree with you now :) See my new post here

BTW, have you got your offer from Google already? I have seen a couple of interview questions from Google provided by you :)

• No i didnt start to find job yet. The problems are from other forums.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.