在C ++中检查数字是否为8的幂
在本节中,我们将看到一个数字是否为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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短