นิยาม
Co-prime numbers: 2 ตัวเลขที่ไม่มีเฉพาะตัวหารร่วมกัน (1 ไม่ใช่ prime)
ตัวอย่าง:
4 และ 5 → co-prime
9 และ 14 → co-prime
18 และ 35 → co-prime
21 และ 57 → ไม่ใช่ co-prime (มี 3 เป็นเฉพาะตัวหารร่วม)
ตัวอย่างโค้ด
const areCoprimes = (num1, num2) => {
const smaller = num1 > num2 ? num1 : num2;
for(let ind = 2; ind < smaller; ind++){
const condition1 = num1 % ind === 0;
const condition2 = num2 % ind === 0;
if(condition1 && condition2){
return false;
};
};
return true;
};
console.log(areCoprimes(4, 5));
console.log(areCoprimes(9, 14));
console.log(areCoprimes(18, 35));
console.log(areCoprimes(21, 57));
ผลลัพธ์
true true true false
คำอธิบาย
วนลูปจาก 2 ถึงตัวเลขที่เล็กกว่า ตรวจสอบว่าเป็นตัวหารของทั้งคู่หรือไม่ (num1 % ind === 0 && num2 % ind === 0) ถ้ามี → false (ไม่ใช่ co-prime)
หมายเหตุ: ใช้ smaller = num1 > num2 ? num1 : num2 ผิด ควรเป็น Math.min(num1, num2) หรือ ternary ให้ถูกต้อง