Here is the program to calculate the Highest Common Factor (HCF -- also known as Greatest Common Divisor) and Lowest Common Multiple (LCM) of two numbers. The code is extremely simple.
int main()
{
unsigned int a, b, i, hcf;
printf("Enter two positive integers > 0: ");
scanf("%d%d", &a, &b);
for(i=1; i<=(a<b? a: b); i++)
{
if(!(a%i) && !(b%i))
{
hcf = i;
}
}
printf("\nThe HCF of %d and %d is %d\n", a, b, hcf);
printf("The LCM of %d and %d is %d\n", a, b, ((a*b)/hcf));
return 0;
}
LCM is calculated using the formula LCM = (a*b)/HCF.
The HCF of 4 and 6 is 2
The LCM of 4 and 6 is 12
Code
#include <stdio.h>int main()
{
unsigned int a, b, i, hcf;
printf("Enter two positive integers > 0: ");
scanf("%d%d", &a, &b);
for(i=1; i<=(a<b? a: b); i++)
{
if(!(a%i) && !(b%i))
{
hcf = i;
}
}
printf("\nThe HCF of %d and %d is %d\n", a, b, hcf);
printf("The LCM of %d and %d is %d\n", a, b, ((a*b)/hcf));
return 0;
}
Explanation
HCF is obtained by dividing both numbers with all natural numbers less than the smallest one and choosing the last common factor (which will be the highest) encountered in the for loop. [The expression (a<b? a: b) chooses the smallest of a and b. The special operator ?: is technically known as conditional operator.]LCM is calculated using the formula LCM = (a*b)/HCF.
Output
Enter two positive integers > 0: 4 6The HCF of 4 and 6 is 2
The LCM of 4 and 6 is 12