首页 文章资讯内容详情

检查互质数-JavaScript

2026-06-04 1 花语

如果两个数字之间不存在共同的素数,则称两个数字为互质数(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

我们需要编写一个包含两个数字的函数,如果它们是互质的,则返回true,否则返回false

示例

让我们为该函数编写代码-

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