Open In App

Check if Two Numbers are Coprime using JavaScript

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are going to learn how we can Check if given two numbers are coprime or not using JavaScript. Co-prime are two integers that have no common factors other than 1. Their greatest common divisor (GCD) is 1. Coprime numbers also known as relatively prime numbers.

Example:

Input: a = 15 and b = 4 
Output: True (as 15 and 4 have only one common factor 1)

Input: a = 28 and b = 14
Output: False (as 28 and 14 have more than one common factor)

These are the following methods:

Iterative Method

Create the function. Use a for loop to iterate from 2 up to the minimum of a and b. This loop checks all possible divisors starting from 2. Check if both a and b are divisible by the current iteration number i. If they are, it means i is a common factor of a and b, so return false i.e. they are not coprime. If loop finishes without finding any common factors the return true.

Example: To demonstrate checking if two numbers are coprime or not using iterative method.

JavaScript
// The iterative approach

function CoprimeIterative(a, b) {
    
    for (let i = 2; i <= Math.min(a, b); i++) {
        // If both a and b are divisible by i
        // means they have a common factor
        if (a % i === 0 && b % i === 0) {
            return false; 
        }
    }
    return true;
}

const num1 = 21;
const num2 = 28;

console.log(`Are ${num1} and ${num2} coprime?
            ${CoprimeIterative(num1, num2)}`);

Output
Are 21 and 28 coprime?
            false

Time Complexity: O(min(a, b))

Space Complexity: O(1)

Euclidean Algorithm

In this approach, we are using Euclidean Algorithm. Create a function GCD and pass a and b as input parameter. Check if b is equal to 0 then return a. else recursively call GCD with b and the remainder of a divided by b. Create another function to check co-prime and pass a and b as input parameter. Call the gcd function with a and b. Return true if the result of gcd(a, b) is 1, indicating that a and b are coprime. Else return false.

Example: To demonstrate checking if two numbers are coprime or not using Euclidean Algorithm.

JavaScript
// Euclidean algorithm

function gcd(a, b) {
     if (b === 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}

function areCoprime(a, b) {
    // If the GCD of two numbers is 1, they are coprime
    return gcd(a, b) === 1;
}


const num1 = 3;
const num2 = 7;

if (areCoprime(num1, num2)) {
    console.log(`${num1} and ${num2} are coprime.`);
} else {
    console.log(`${num1} and ${num2} are not coprime.`);
}

Output
3 and 7 are coprime.

Time Complexity: O(min(a, b))

Space Complexity: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads