Algorithm
-
Input: Accept two numbers as input, let's call them
num1
andnum2
. -
Initialization: Initialize a variable
hcf
to 1. -
Loop: Start a loop that runs from 1 to the minimum of
num1
andnum2
. Let's call the loop variablei
.a. Check if both
num1
andnum2
are divisible byi
.b. If they are, update the
hcf
toi
. -
Output: The value of
hcf
after the loop is the highest common factor (HCF) or greatest common divisor (GCD) ofnum1
andnum2
.
Code Examples
#1 Code Example- Find HCF using for Loop
Code -
Javascript Programming
// program to find the HCF or GCD of two integers
let hcf;
// take input
const number1 = prompt('Enter a first positive integer: ');
const number2 = prompt('Enter a second positive integer: ');
// looping from 1 to number1 and number2
for (let i = 1; i < = number1 && i <= number2; i++) {
// check if is factor of both integers
if( number1 % i == 0 && number2 % i == 0) {
hcf = i;
}
}
// display the hcf
console.log(`HCF of ${number1} and ${number2} is ${hcf}.`);
Copy The Code &
Try With Live Editor
Output
Enter a second integer: 72
HCF of 60 and 72 is 12.
#2 Code Example- HCF using while Loop and if...else
Code -
Javascript Programming
// program to find the HCF or GCD of two integers
// take input
let number1 = prompt('Enter a first positive integer: ');
let number2 = prompt('Enter a second positive integer: ');
// looping until both numbers are equal
while(number1 != number2){
if(number1 > number2) {
number1 -= number2;
}
else {
number2 -= number1;
}
}
// display the hcf
console.log(`HCF is ${number1}`);
Copy The Code &
Try With Live Editor
Output
Enter a second integer: 72
HCF is 12
Demonstration
JavaScript Programing Example to Find HCF or GCD-DevsEnv