Question
Given an integer, write a function to determine if it is a power of three.
Follow up
Could you do it without using any loop / recursion?
Java Code
/**
* 版本一:判断因子法
* 先找到整数范围内最大的3的幂maxNum,再判断n是否能被maxNum整除
* 由于maxNum的所有因子都是3,而且3是素数,那么当且仅当n的所有因子也是3时,才能被整除
*/
public boolean isPowerOfThree2(int n) {
if(n < 1) return false;
//找到整型范围内最大的3的幂
long maxNum = 27;
while(maxNum < Integer.MAX_VALUE)
maxNum *= 3;
//此时maxNum刚超出整型范围,需要先去掉一个因子3,再判断其能否被n整除
return (maxNum/3) % n == 0;
}
//版本二:直接利用log函数判断
public boolean isPowerOfThree(int n) {
if(n < 1) return false;
//必须用10计算换底公式,如果用e换底会有较大的计算精度误差
double pow = Math.log10(n) / Math.log10(3);
return pow == (int)pow;
}