在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 生日广州男生祝福语简短