Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Understanding Co-prime Numbers
Two numbers are co-prime if their greatest common divisor (GCD) is 1. This means they share no common factors other than 1.
Method 1: Using Loop to Check Common Factors
This approach iterates through all possible divisors and checks if both numbers share any common factor:
const areCoprimes = (num1, num2) => {
const smaller = num1 > num2 ? num2 : num1;
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
Method 2: Using GCD (More Efficient)
A more efficient approach uses the Euclidean algorithm to find the GCD. If GCD equals 1, the numbers are co-prime:
const gcd = (a, b) => {
return b === 0 ? a : gcd(b, a % b);
};
const areCoprimes = (num1, num2) => {
return gcd(Math.abs(num1), Math.abs(num2)) === 1;
};
console.log(areCoprimes(4, 5)); // true
console.log(areCoprimes(9, 14)); // true
console.log(areCoprimes(18, 35)); // true
console.log(areCoprimes(21, 57)); // false
console.log(areCoprimes(15, 25)); // false (GCD = 5)
true true true false false
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Loop Method | O(min(a,b)) | O(1) | Small numbers |
| GCD Method | O(log(min(a,b))) | O(log(min(a,b))) | Large numbers |
Conclusion
The GCD method is more efficient for large numbers, while the loop method is simpler to understand. Both approaches correctly identify co-prime numbers by checking for common factors.
