Write a JavaScript Program to Find HCF or GCD

In mathematics, the Highest Common Factor (HCF) or Greatest Common Divisor (GCD) of two or more numbers is the largest positive integer that divides the numbers without leaving any remainder.

Finding the HCF/GCD of two or more numbers is a common mathematical operation, and in this tutorial, we’ll be exploring how to do it using JavaScript.

To find the HCF/GCD of two or more numbers using JavaScript, we can use the Euclidean algorithm, which is an efficient way of finding the greatest common divisor of two integers.

The Euclidean algorithm works as follows: given two integers a and b, we find their remainder r when a is divided by b. If r is zero, then b is the greatest common divisor of a and b. If r is not zero, then we replace a with b and b with r, and repeat the process until r becomes zero.

Here is the JavaScript code to find the HCF/GCD of two numbers using the Euclidean algorithm:

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

// Example usage
console.log(gcd(12, 18)); // Output: 6

In this code, the gcd function takes two arguments a and b, which are the two numbers we want to find the HCF/GCD of.

If b is zero, then a is the greatest common divisor, and we return a. Otherwise, we recursively call the gcd function with b as the first argument and the remainder of a divided by b as the second argument, until we reach the case where b is zero.

To find the HCF/GCD of more than two numbers, we can use the fact that the HCF/GCD of a set of numbers is the same as the HCF/GCD of the HCF/GCD of the first two numbers and the remaining numbers in the set. Here is the JavaScript code to find the HCF/GCD of any number of numbers:

function gcdArray(numbers) {
  let result = numbers[0];
  for (let i = 1; i < numbers.length; i++) {
    result = gcd(result, numbers[i]);
  }
  return result;
}

// Example usage
console.log(gcdArray([12, 18, 24])); // Output: 6

In this code, the gcdArray function takes an array of numbers as its argument.

We initialize result to the first number in the array, and then loop through the remaining numbers, calling the gcd function with result and the current number, and storing the result back in result.

Finally, we return result, which is the HCF/GCD of all the numbers in the array.

In conclusion, finding the HCF/GCD of two or more numbers is a common mathematical operation that can be easily done using the Euclidean algorithm in JavaScript.

The above code snippets show how to implement this algorithm in JavaScript, both for two numbers and for any number of numbers.