检查互素数 - JavaScript
如果两个数字中不存在相同的素因数,则称这两个数字互质(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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP