How to Find the Highest Common Factor of Two Numbers in JavaScript?

Estimated read time 1 min read

To find the highest common factor (HCF) of two numbers in JavaScript, you can use a while loop to repeatedly divide the larger number by the smaller number until the remainder is 0. The HCF is then the smaller number before the division.

Here’s an example:

function highestCommonFactor(a, b) {
  let [larger, smaller] = a > b ? [a, b] : [b, a];
  let remainder = larger % smaller;
  
  while (remainder !== 0) {
    larger = smaller;
    smaller = remainder;
    remainder = larger % smaller;
  }
  
  return smaller;
}

console.log(highestCommonFactor(36, 48)); // Output: 12

In this example, the highestCommonFactor function takes two arguments a and b and uses a ternary operator to determine which number is larger and which is smaller. The while loop is then used to repeatedly divide the larger number by the smaller number until the remainder is 0. The HCF is then the smaller number before the division. In this case, the HCF of 36 and 48 is 12.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply