ในส่วนนี้เราจะมาดูกันว่าตัวเลขเป็นเลขยกกำลัง 8 หรือไม่ โดยใช้วิธีที่ง่ายกว่านี้ หากมีตัวเลขเช่น 4096 โปรแกรมจะคืนค่า จริง เนื่องจากนี่คือยกกำลัง 8
เคล็ดลับเป็นเรื่องง่าย เราจะคำนวณ log8(num) หากเป็นจำนวนเต็ม n คือกำลังของ 8 ในที่นี้เราจะใช้ฟังก์ชัน tranc(n) เพื่อค้นหาจำนวนเต็มที่ใกล้เคียงที่สุดของค่าสองเท่า
ตัวอย่าง
#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