Checking for coprime numbers in JavaScript


Two numbers are said to be co-primes if there exists no common prime factor amongst them (1 is not a prime number).

We are required to write a function that takes in two numbers and returns true if they are coprimes otherwise returns false.

Example

The code for this will be −

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));

Output

The output in the console −

true
true
true
false

Updated on: 14-Oct-2020

678 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements