Semiprime คือจำนวนประกอบ (composite) ที่เป็นผลคูณของจำนวนเฉพาะ 2 ตัว (อาจเป็นตัวเดียวกัน เช่น 4=2×2, 9=3×3)
ตัวอย่าง
6 = 2×3 ✓ 15 = 3×5 ✓ 10 = 2×5 ✓ 77 = 7×11 ✓ 4 = 2² ✓ 9 = 3² ✓
ตัวอย่างโค้ด
const num = 141;
const checkSemiprime = num => {
let cnt = 0;
for (let i = 2; cnt < 2 && i * i <= num; ++i) {
while (num % i == 0) {
num /= i;
++cnt;
}
}
if (num > 1) ++cnt;
return cnt === 2;
};
console.log(checkSemiprime(num));
การทำงาน
- แยกตัวประกอบเฉพาะ (prime factorization)
- นับจำนวนตัวประกอบเฉพาะ (รวมซ้ำ)
- ถ้ารวมได้ 2 ตัว → semiprime
ผลลัพธ์
true
141 = 3 × 47 (ทั้งคู่เป็นจำนวนเฉพาะ) → semiprime