Open In App

JavaScript Program to Find GCD or HCF of Two Numbers

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both numbers without leaving a remainder.

GCD ( a, b ) = [ |a.b| ] / [ lcm(a, b) ]
or,
HCF of factors = Product of the Numbers/ LCM of numbers

Example:

Input: a = 20, b = 28
Output: 4
Explanation: The factors of 20 are 1, 2, 4, 5, 10 and 20.
The factors of 28 are 1, 2, 4, 7, 14 and 28. Among these factors,
1, 2 and 4 are the common factors of both 20 and 28.
The greatest among the common factors is 4.

There are several methods that to Find GCD or HCF of Two Numbers in JavaScript, which are listed below:

Using for Loop

In this approach we are using a for loop to find GCD/HCF, iterating from 1 to the minimum of the two numbers. Update GCD when both numbers are divisible.

Syntax:

for ( variable of iterableObjectName) {
. . .
}

Example:

Javascript




function myFunction(a, b) {
    let smaller = Math.min(a, b);
    let hcf = 1;
 
    for (let i = 1; i <= smaller; i++) {
        if (a % i === 0 && b % i === 0) {
            hcf = i;
        }
    }
 
    return hcf;
}
 
const num1 = 20;
const num2 = 12;
 
console.log("GCD of the giving numbers(20,12) is:",
    myFunction(num1, num2));


Output

GCD of the giving numbers(20,12) is: 4

Using the Recursive method

In this approach, the recursive function myFunction calculates GCD using the Euclidean algorithm. If b=0, returns a; otherwise, recursively calls with b and remainder of a/b.

Syntax:

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

Example: In this example, we are using the above-explained approach.

Javascript




function myFunction(a, b) {
    if (b === 0) {
        return a;
    }
    return myFunction(b, a % b);
}
 
let num1 = 12;
let num2 = 18;
let result = myFunction(num1, num2);
console.log(`GCD of ${num1} and ${num2} is ${result}`);


Output

GCD of 12 and 18 is 6

Using if…else Statements

Here, we will use if…else statement to Find GCD or HCF of Two Numbers

Example: Below is an example.

Javascript




// Function to find GCD using if...else statement
function findGCDIfElse(a, b) {
    let gcd;
 
    if (a === 0) {
        gcd = b;
    } else if (b === 0) {
        gcd = a;
    } else {
        while (a !== b) {
            if (a > b) {
                a -= b;
            } else {
                b -= a;
            }
        }
        gcd = a;
    }
 
    return gcd;
}
 
// Example usage
let num1 = 36;
let num2 = 48;
let resultIfElse = findGCDIfElse(num1, num2);
console.log(`GCD of ${num1} and ${num2} : ${resultIfElse}`);


Output

GCD of 36 and 48 : 12



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads