|
| 1 | +/* |
| 2 | + Problem statement and Explanation : https://en.wikipedia.org/wiki/Coprime_integers |
| 3 | +
|
| 4 | + In number theory, two integers a and b are coprime, relatively prime or |
| 5 | + mutually prime if the only positive integer that is a divisor of both |
| 6 | + of them is Consequently, any prime number that divides one of a |
| 7 | + or b does not divide the other. This is equivalent to their greatest |
| 8 | + common divisor (gcd) being. One says also a is prime to b or a |
| 9 | + is coprime with b. |
| 10 | +*/ |
| 11 | + |
| 12 | +// Here we use a GetEuclidGCD method as a utility. |
| 13 | +const GetEuclidGCD = (arg1, arg2) => { |
| 14 | + let less = arg1 > arg2 ? arg2 : arg1 |
| 15 | + for (less; less >= 2; less--) { |
| 16 | + if ((arg1 % less === 0) && (arg2 % less === 0)) return (less) |
| 17 | + } |
| 18 | + return (less) |
| 19 | +} |
| 20 | + |
| 21 | +// CoPrimeCheck function return the boolean in respect of the given number is co-prime or not. |
| 22 | +/** |
| 23 | + * CoPrimeCheck function return the boolean in respect of the given number is co-prime or not. |
| 24 | + * @param {Number} firstNumber first number for checking is prime or not. |
| 25 | + * @param {Number} secondNumber second number for checking is prime or not. |
| 26 | + * @returns return correspond boolean value, if both number are co-prime return `true`, else return `false`. |
| 27 | + */ |
| 28 | +const CoPrimeCheck = (firstNumber, secondNumber) => { |
| 29 | + // firstly, check that input is a number or not. |
| 30 | + if (typeof firstNumber !== 'number' || typeof secondNumber !== 'number') { |
| 31 | + return new TypeError('Argument is not a number.') |
| 32 | + } |
| 33 | + /* |
| 34 | + This is the most efficient algorithm for checking co-primes |
| 35 | + if the GCD of both the numbers is 1 that means they are co-primes. |
| 36 | + */ |
| 37 | + return GetEuclidGCD(firstNumber, secondNumber) === 1 |
| 38 | +} |
| 39 | + |
| 40 | +module.exports = CoPrimeCheck |
0 commit comments