Skip to content

JavaScript Find HCF Example

Ramesh Fadatare edited this page Aug 11, 2020 · 1 revision

In this example, you will learn to write a program that finds HCF or GCD in JavaScript.

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

For example, the HCF of 60 and 72 is 12.

JavaScript Find HCF Example

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)
}

var num1 = 27;
var num2 = 36;

console.log('HCF of ' + num1 + ' and ' + num2 + ' is ' + findHCF(num1, num2));

Output

Clone this wiki locally