在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 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语