Signup/Sign In
PUBLISHED ON: MARCH 15, 2023

JavaScript Program to Find HCF or GCD

Hello Everyone!

In mathematics, the biggest positive integer that divides two or more integers without producing a remainder is called the highest common factor (HCF) or greatest common divisor (GCD). It is a crucial idea in number theory and has many uses in computer science, especially in methods for data compression and encryption.

This tutorial will teach us how to write a program in JavaScript to check Find HCF or GCD. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.

HCF

The Highest Common Factor (HCF) or Greatest Common Divisor (GCD) of two integers is the largest integer that can exactly divide both integers, basically without a reminder.

The HCF of 36 and 48 will be 12.

Approach

In the program, the user is asked to enter two numbers.

The loop is used to iterate from the smallest number to the largest number, basically, it is used to subtract the smaller number from the greater number until both values do not become equal.

Code

// JavaScript program to find the HCF or GCD of two integers

let num1 = prompt('Enter a first integer: ');
let num2 = prompt('Enter a second  integer: ');

//until both numbers are equal
console.log("HCF of both the numbers is ")
while(num1 != num2){
    if(num1 > num2) 
        num1 -= num2;
    
    else 
        num2 -= num1;
}
console.log(num1);


Enter a first integer: 60
Enter a second integer: 36
HCF of both the numbers is 12

conclusion

In conclusion, finding the HCF or GCD of two numbers is an important task in mathematics and computer science. In this article, we discussed how to write a JavaScript program to find the HCF or GCD using the Euclidean algorithm. We also covered some examples and edge cases that can occur when finding the HCF or GCD of two numbers. With this knowledge, you can implement this algorithm in your own programs and use it in various applications.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.