นับจำนวนตัวหาร (Factors/Divisors) ของตัวเลขที่หารลงตัว
ตัวอย่าง
12 → Factors: 1, 2, 3, 4, 6, 12 → Count: 6
ตัวอย่างโค้ด
const countFactors = num => {
let count = 0;
for (let i = 1; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
count += (i === num / i) ? 1 : 2; // ตัวหารคู่ (i, num/i)
}
}
return count;
};
console.log(countFactors(12)); // 6
console.log(countFactors(2)); // 2
console.log(countFactors(454)); // 4
console.log(countFactors(99)); // 6
ผลลัพธ์
6 2 4 6
คำอธิบายอัลกอริทึม
- ลูปแค่ถึง √n เพราะตัวหารมาคู่กัน (i, n/i)
- ถ้า i² = n (Perfect Square) นับแค่ 1 ตัว
- Complexity: O(√n) เร็วกว่าลูปถึง n/2 มาก
โค้ดต้นฉบับลูปถึง n/2 และเริ่มจาก 2 (พลาด 1 และตัวเลขตัวเอง) แล้วบวก 2 ท้ายสุด