กล่าวได้ว่าจำนวนสองจำนวนเป็นจำนวนเฉพาะร่วมหากไม่มีตัวประกอบเฉพาะร่วมกันในจำนวนนั้น (1 ไม่ใช่จำนวนเฉพาะ)
ตัวอย่างเช่น −
4 and 5 are co-primes 9 and 14 are co-primes 18 and 35 are co-primes 21 and 57 are not co-prime because they have 3 as the common prime factor
เราจำเป็นต้องเขียนฟังก์ชันที่ใช้ตัวเลขสองตัวและคืนค่า จริง หากเป็น co-primes มิฉะนั้นจะคืนค่าเท็จ
ตัวอย่าง
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
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