Algorithm


  1. Input: Accept two numbers as input, let's call them num1 and num2.

  2. Initialization: Initialize a variable hcf to 1.

  3. Loop: Start a loop that runs from 1 to the minimum of num1 and num2. Let's call the loop variable i.

    a. Check if both num1 and num2 are divisible by i.

    b. If they are, update the hcf to i.

  4. Output: The value of hcf after the loop is the highest common factor (HCF) or greatest common divisor (GCD) of num1 and num2.

 

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

x
+
cmd
Enter a first integer: 60
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

x
+
cmd
Enter a first integer: 60
Enter a second integer: 72
HCF is 12
Advertisements

Demonstration


JavaScript Programing Example to Find HCF or GCD-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way