เราต้องเขียนฟังก์ชันที่รับจำนวนเต็มบวก คืนอาร์เรย์ของตัวเลขที่หารลงตัว (factors) ทั้งหมด
ตัวอย่าง: 12 → [1, 2, 3, 4, 6, 12]
ตัวอย่างโค้ด
const findFactors = (num = 1) => {
let half = Math.floor(num / 2);
const res = [1];
let i, j;
num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
for (i; i <= half; i += j) {
if (num % i === 0) { res.push(i); }
}
res.push(num);
return res;
};
console.log(findFactors(12));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
[ 1, 2, 3, 4, 6, 12 ]