HCF

The greatest common divisor of two or more numerical values is called the highest common factor (HCF). In other words, the largest number that can completely divide two or more numbers is the highest common factor.

Logic

Let declare one temporary variable hcf by 1, we are going to use this variable to store HCF.

Here we are calculating HCF of two user given numbers, after taking both the numbers (num1, num2) from the user, we have to find out which number is smaller, we store the minimum one in the variable min.

Now we start one loop from 1 to min (Minimum between both numbers), and inside the loop, we have to check if both the numbers are completely divisible by current number “i” or not. If yes then we update temporary variable hcf by current number “i”, otherwise continue with the loop.

Once the loop is over simply print the variable hcf containing the highest common factor of num1 and num2.

Program

#include <stdio.h>

int main() {

    int i, num1, num2, min, hcf=1;

    // Take two numbers from user
    printf("Enter two numbers : ");
    scanf("%d", &num1);
    scanf("%d", &num2);

    // Find minimum between two numbers
    min = num1;
    if(num2 < num1) {
        min = num2;
    }

    for(i = 1; i <= min; i++) {

        if((num1 % i) == 0 && (num2 % i) == 0) {
            hcf = i;
        }
    }

    printf("\nHCF of %d and %d : %d", num1, num2, hcf);

    return 0;
}

Output

Enter two numbers : 12 30
HCF of 12 and 30 : 6