JavaScript(JS) JS find hcf or gcd

www.‮itfigi‬dea.com

To find the highest common factor (HCF) or greatest common divisor (GCD) of two or more numbers, we can use the Euclidean algorithm. The algorithm involves finding the remainder of the larger number divided by the smaller number repeatedly until the remainder is zero. The divisor at the point when the remainder becomes zero is the HCF or GCD of the two numbers.

Here's an implementation of the Euclidean algorithm in JavaScript:

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

This function takes two numbers, a and b, as parameters and returns their HCF. It does this by recursively calling itself with the parameters b and a % b until b becomes zero. At this point, the function returns a, which is the HCF.

To find the HCF or GCD of more than two numbers, we can modify the function to take an array of numbers as a parameter:

function findHCF(numbers) {
  function getHCF(a, b) {
    if (b === 0) {
      return a;
    } else {
      return getHCF(b, a % b);
    }
  }

  return numbers.reduce(function(currentHCF, nextNumber) {
    return getHCF(currentHCF, nextNumber);
  });
}

This function takes an array of numbers as a parameter and uses the reduce method to iterate over the array and find the HCF of all the numbers. The getHCF function is defined inside findHCF and is used by reduce to find the HCF of the current HCF and the next number in the array. The final result is the HCF of all the numbers in the array.