检查数字是否为 C++ 中的 8 次幂
在本节中,我们将学习使用一些更简单的方法,检查一个数字是否是 8 的幂。如果存在像 4096 这样的数字,那么程序将返回真,因为这是 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP