GCD of two numbers | Program to find the GCD or HCF of two numbers
The GCD (Greatest Common Divisor), also known as the HCF (Highest Common Factor), of two integers is the largest integer that divides both numbers without leaving a remainder. This concept is widely used in mathematics, cryptography, and computational tasks.
What Is the GCD of Two Numbers?
For example, the GCD of 181818 and 242424 is 666, as 666 is the largest number that divides both 181818 and 242424 without a remainder.
Methods to Calculate GCD
Here are three common methods to find the GCD of two numbers:
1. Iterative Approach
This method uses a simple loop to find the largest divisor of both numbers.Algorithm:
Identify the smaller number between the two inputs.
Iterate from the smaller number down to 111.
Find the first number that divides both inputs without a remainder.
Code Implementation (C):
c
#include<stdio.h>intfindGCD(int a, int b) {
int small = a > b ? b : a;
for (int i = small; i >= 1; i–) {
if (a % i == 0 && b % i == 0) {
return i;
}
}
return1; // Default case if no other divisor is found
}intmain() {
int num1 = 18, num2 = 24;
printf(“GCD of %d and %d is: %d\n”, num1, num2, findGCD(num1, num2));
return0;
}
2. Using Recursion
The recursive method applies Euclid’s Algorithm, which is based on the property:GCD(a,b)=GCD(b,a%b)\text{GCD}(a, b) = \text{GCD}(b, a \% b)GCD(a,b)=GCD(b,a%b)The recursion terminates when b=0b = 0b=0, at which point aaa is the GCD.Code Implementation (C):
c
#include<stdio.h>intgcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}intmain() {
int num1 = 18, num2 = 24;
printf(“GCD of %d and %d is: %d\n”, num1, num2, gcd(num1, num2));
return0;
}
3. Using Command-Line Arguments
This approach is particularly useful for running the program directly from a terminal, where the inputs are provided as arguments.Code Implementation (C):
c
#include<stdio.h>#include<stdlib.h>intmain(int argc, char *argv[]) {
if (argc != 3) {
printf(“Usage: %s <num1> <num2>\n”, argv[0]);
return1;
}int a = atoi(argv[1]);
int b = atoi(argv[2]);
int small = a > b ? b : a;for (int i = small; i >= 1; i–) {
if (a % i == 0 && b % i == 0) {
printf(“GCD of %d and %d is: %d\n”, a, b, i);
return0;
}
}
return1;
}
Fractions: Simplifying fractions to their lowest terms.
LCM Calculation: GCD helps compute the LCM using the formula: LCM(a,b)=∣a⋅b∣GCD(a,b)\text{LCM}(a, b) = \frac{|a \cdot b|}{\text{GCD}(a, b)}LCM(a,b)=GCD(a,b)∣a⋅b∣