JavaScript program to find GCD or HCF

In this program, you will take two integer inputs from the user and find the highest command factor(HCF) or greatest command factor(GCD) of two numbers.

HCF and GCD both are the same things, which means the largest integer that can exactly divide both integers

for example, HCF or GCD of 10 and 15 is 5

find GCD or HCF by using for loop


 // take input from user
  const num1 = prompt('Enter a first positive number: ');
  const num2 = prompt('Enter a second positive number: ');
  // iterate for loop from 1 to num1 and num2
  for (let i = 1; i <= num1 && i <= num2; i++) {

	 // check if variable i is factor of both num1 and num2
	 if( num1 % i == 0 && num2 % i == 0) {
		 hcf = i;
	  }
  }
  // display the hcf
  document.write("highest command factor(HCF) of "+num1+" and "+num2+" is "+hcf);

output

Enter a first positive number: 10
Enter a second positive number: 15
highest command factor(HCF) of 10 and 15 is 5

HCF using HTML form


<html>
<body>
<script>
function HCF() {
  // take input from user
  const num1 = prompt('Enter a first positive number: ');
  const num2 = prompt('Enter a second positive number: ');
  // iterate for loop from 1 to num1 and num2
  for (let i = 1; i <= num1 && i <= num2; i++) {

    // check if variable i is factor of both num1 and num2
    if (num1 % i == 0 && num2 % i == 0) {
      hcf = i;
    }
  }
  // display the hcf
  document.write("highest command factor(HCF) of " + num1 + " and" + num2 + " is " + hcf);
}
</script>
 <form>
   <input type="button" value="ArmstrongNo" onclick="HCF();" />
    </form>
</body>
</html>
Run now