Checking for co-prime numbers - JavaScript


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

For example −

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

We are required to write a function that takes in two numbers and returns true if they are co-primes otherwise returns false

Example

Let’s write the code for this function −

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

Following is the output in the console −

true
true
true
false

Updated on: 14-Sep-2020

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements