檢查互素數 - 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