ภาพรวม
บทความนี้สาธิตวิธีหาตัวเลขที่เป็นกำลังของ 2 (2ⁿ) ที่ใกล้ที่สุดกับตัวเลขที่กำหนด เช่น 145 -> 128 (2⁷)
การนำไปใช้
const nearestPowerOfTwo = (num) => {
// จัดการตัวเลขติดลบ
if (num < 0) num *= -1;
let base = 1;
while (base < num) {
// ตรวจสอบว่าฐานปัจจุบันใกล้กว่าฐานถัดไป
if (num - base < Math.floor(base / 2)) {
return base;
}
base *= 2;
}
return base;
};
console.log(nearestPowerOfTwo(145)); // 128
ผลลัพธ์
128
วิธีการทางคณิตศาสตร์ (เร็วกว่า)
const nearestPowerOfTwoMath = (num) => {
if (num <= 0) return 1;
const log2 = Math.log2(num);
const lower = Math.pow(2, Math.floor(log2));
const upper = Math.pow(2, Math.ceil(log2));
// เปรียบเทียบระยะทาง
return (num - lower) < (upper - num) ? lower : upper;
};
วิธีการใช้ Bitwise (เร็วที่สุด สำหรับ Integer)
const nearestPowerOfTwoBitwise = (num) => {
if (num <= 0) return 1;
num = Math.floor(num);
// หากเป็นกำลังของ 2 อยู่แล้ว
if ((num & (num - 1)) === 0) return num;
// หา MSB (Most Significant Bit)
let msb = 1;
while (msb <= num) msb <<= 1;
const lower = msb >> 1;
return (num - lower) < (msb - num) ? lower : msb;
};
ตารางกำลังของ 2 (อ้างอิง)
| n | 2ⁿ | n | 2ⁿ |
|---|---|---|---|
| 0 | 1 | 16 | 65,536 |
| 1 | 2 | 17 | 131,072 |
| 2 | 4 | 18 | 262,144 |
| 3 | 8 | 19 | 524,288 |
| 4 | 16 | 20 | 1,048,576 |
| 5 | 32 | 21 | 2,097,152 |
| 6 | 64 | 22 | 4,194,304 |
| 7 | 128 | 23 | 8,388,608 |
| 8 | 256 | 24 | 16,777,216 |
| 9 | 512 | 25 | 33,554,432 |
| 10 | 1,024 | 26 | 67,108,864 |
| 11 | 2,048 | 27 | 134,217,728 |
| 12 | 4,096 | 28 | 268,435,456 |
| 13 | 8,192 | 29 | 536,870,912 |
| 14 | 16,384 | 30 | 1,073,741,824 |
| 15 | 32,768 | 31 | 2,147,483,648 |
การประยุกต์ใช้
- Memory Allocation (หน่วยความจำจัดสรรเป็นบล็อกกำลังของ 2)
- Texture Sizes ใน WebGL/OpenGL
- Hash Table Sizing
- FFT (Fast Fourier Transform) Buffer Sizes
- Binary Tree Array Representation