Find Hcf Algorithm

The Find HCF Algorithm, also known as the Greatest Common Divisor (GCD) algorithm or the Euclidean algorithm, is a fundamental mathematical method used to find the highest common factor (HCF) or greatest common divisor (GCD) of two or more integers. The HCF is the largest positive integer that divides each of the given numbers without leaving any remainder. This algorithm has a wide range of applications, including simplifying fractions, solving Diophantine equations, and computing least common multiples (LCM). The Find HCF Algorithm works by performing repeated divisions on the given integers and then finding the remainder. To find the HCF of two integers, the algorithm divides the larger number by the smaller number and takes the remainder. Next, it divides the smaller number by the remainder obtained in the previous step, and this process is repeated until the remainder becomes zero. At this point, the HCF is the non-zero remainder obtained in the last division. The algorithm can also be extended to find the HCF of more than two integers by first finding the HCF of two integers, and then finding the HCF of the result and the next integer, continuing in this manner until all integers have been considered. The Euclidean algorithm is computationally efficient and can be implemented using recursion or iterative methods in various programming languages.
/*
    author: redfly1
    More about HCF:
        https://en.wikipedia.org/wiki/Greatest_common_divisor
 */

function findHCF (x, y) {
  // If the input numbers are less than 1 return an error message.
  if (x < 1 || y < 1) {
    return 'Please enter values greater than zero.'
  }

  // If the input numbers are not integers return an error message.
  if (x !== Math.round(x) || y !== Math.round(y)) {
    return 'Please enter whole numbers.'
  }

  // Now apply Euclid's algorithm to the two numbers.
  while (Math.max(x, y) % Math.min(x, y) !== 0) {
    if (x > y) {
      x %= y
    } else {
      y %= x
    }
  }

  // When the while loop finishes the minimum of x and y is the HCF.
  return Math.min(x, y)
}
console.log(findHCF(27, 36))

LANGUAGE:

DARK MODE: