Introduction
In this blog, we will discuss the solution to the problem of finding the HCF(Highest Common Factor) of two numbers. We will discuss three different C program to find HCF of two numbers, and their time and space complexities.
Before discussing the C program to find HCF of two numbers, Let’s first discuss what HCF(Highest Common Factor) means.
HCF(Highest Common Factor) is also known as GCF(Greatest Common Factor) or GCD(Greatest Common Divisor). HCF of two numbers is the greatest integer that divides both of them completely, i.e., the remainder is zero.
For Example:

The different methods to find HCF of two numbers are:
- Linear Search for HCF
- Repeated Subtraction
- Euclidean Approach
Method 1: Linear Hunt
The approach is to check for each number starting from 1 to the minimum and return the maximum number that completely divides both numbers.
Algorithm
- Initialize a variable ‘hcf’ to return the answer i.e., hcf=1
- Find the minimum of two numbers, ‘n1’ and ‘n2’
- Run a loop from 1 to ‘min’ value
- For each value of ‘i’, check if ‘i’ completely divides ‘n1’ and ‘n2’, then set the value of ‘hcf’ to ‘i’
- Return value of ‘hcf’ variable
Implementation
/* C program to find HCF of two number using iterative approach */
#include <stdio.h>
int hcf(int n1, int n2)
{
int min = (n1<n2) ? n1 : n2;
int hcf=1;
for(int i=1; i<=min; i++)
{
if(n1%i==0 && n2%i==0)
{
hcf = i;
}
}
return hcf;
}
int main()
{
int n1,n2;
n1 = 40, n2 = 10;
printf(" Using iterative Approach : \n");
printf(" HCF of %d and %d = %d\n", n1, n2, hcf(n1, n2));
n1 = 36, n2 = 60;
printf(" HCF of %d and %d = %d\n", n1, n2, hcf(n1, n2));
n1 = 24, n2 = 12;
printf(" HCF of %d and %d = %d\n", n1, n2, hcf(n1, n2));
return 0;
}
Output
Time and Space Complexity
Code block inside the for loop takes O(min) time complexity, therefore, the Time Complexity is O(min(n1,n2)), as we have only used variables that take constant space, therefore, the Space Complexity is O(1).
Also Read - Dynamic Array in C