在本节中,我们将看到一个数字是否为8的乘方或不使用某种更简单的方法。如果有4096之类的数字,则程序将返回true,因为这是8的幂。
诀窍很简单。我们将计算log8(num)。如果这是整数,则n是8的幂。在这里,我们将使用tranc(n)函数查找double值的最接近整数。
#include <iostream>
#include <cmath>
using namespace std;
bool isPowerOfEight(int n) {
double val = log(n)/log(8); //get log n to the base 8
return (val - trunc(val) < 0.000001);
}
int main() {
int number = 4096;
if(isPowerOfEight(number)){
cout << number << " is power of 8";
} else {
cout << number << " is not power of 8";
}
}输出结果
4096 is power of 8