Algorithm to Find the HCF (Highest Common Factor) of Two Numbers
- Input: Two numbers,
a
andb
. - Initialize:
hcf
to 1. - Loop: From
i = 1
to the minimum ofa
andb
:
- If both
a
andb
are divisible byi
, sethcf
toi
.
- Output: The value of
hcf
.
C Program to Find the HCF of Two Numbers
#include <stdio.h>
// Function to find the HCF of two numbers
int findHCF(int a, int b) {
int hcf = 1; // Initialize HCF to 1
// Find the minimum of a and b
int min = (a < b) ? a : b;
// Loop from 1 to the minimum of a and b
for (int i = 1; i <= min; i++) {
// If both a and b are divisible by i, update hcf
if (a % i == 0 && b % i == 0) {
hcf = i;
}
}
return hcf; // Return the HCF
}
int main() {
int num1, num2;
// Input two numbers from the user
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Call the function to find the HCF
int hcf = findHCF(num1, num2);
// Print the HCF
printf("The HCF of %d and %d is: %d\n", num1, num2, hcf);
return 0;
}
Explanation:
- Function Definition (
findHCF
):
- This function takes two integers
a
andb
as input. - It initializes
hcf
to 1, which will store the highest common factor. - The variable
min
is set to the minimum ofa
andb
to limit the loop. - The
for
loop iterates from 1 tomin
. For eachi
, it checks if botha
andb
are divisible byi
. If so, it updateshcf
toi
. - Finally, the function returns the value of
hcf
.
- Main Function (
main
):
- The
main
function prompts the user to enter two numbers. - It reads the input numbers using
scanf
. - It then calls the
findHCF
function to compute the HCF of the two numbers. - Finally, it prints the HCF.
This program uses a simple iterative method to find the HCF by checking all numbers from 1 to the minimum of the two given numbers.