ในส่วนนี้เราจะมาดูวิธีตรวจสอบว่า Number เป็น Power of 8 หรือไม่ด้วยวิธีง่ายๆ ถ้า Number เช่น 4096 โปรแกรมจะคืนค่า true เพราะ 4096 = 8^4
ทริกง่ายๆ: คำนวณ log8(num) ถ้าเป็น Integer แสดงว่า n เป็น Power of 8 ใช้ trunc(n) หา Integer ที่ใกล้ที่สุดของค่า Double
ตัวอย่างโค้ด C++
#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