HCF/GCD of Two Numbers
Find the highest common factor (HCF) or greatest common divisor (GCD) of two given positive integers.
Understand the Problem
Problem Statement
The program must accept two numbers X and Y and then print their HCF/GCD.
Input Format:
The first line denotes the value of X.
The second line denotes the value of Y.
Output Format:
The first line contains the HCF of X and Y.
Constraints
- 1 <= X <= 999999
- 1 <= Y <= 999999
- Both X and Y are positive integers
- Program must handle large numbers efficiently
Examples
Example 1
Input
30
40Output
10Explanation
The factors of 30 are 1, 2, 3, 5, 6, 10, 15, 30.
The factors of 40 are 1, 2, 4, 5, 8, 10, 20, 40.
The highest common factor is 10.
The factors of 40 are 1, 2, 4, 5, 8, 10, 20, 40.
The highest common factor is 10.
Example 2
Input
15
10Output
5Explanation
The factors of 15 are 1, 3, 5, 15.
The factors of 10 are 1, 2, 5, 10.
The highest common factor is 5.
The factors of 10 are 1, 2, 5, 10.
The highest common factor is 5.
Example 3
Input
48
18Output
6Explanation
Using Euclidean algorithm:
48 % 18 = 12
18 % 12 = 6
12 % 6 = 0
So HCF is 6.
48 % 18 = 12
18 % 12 = 6
12 % 6 = 0
So HCF is 6.
Solution
#include <stdio.h>
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int x, y;
scanf("%d", &x);
scanf("%d", &y);
printf("%d", gcd(x, y));
return 0;
}Time:O(log min(X, Y)) - The number of iterations is logarithmic in the smaller number
Space:O(1) - Uses only constant extra space for variables
Approach:
Step-by-step explanation:
- Function gcd(): Implements Euclidean algorithm
- While loop: Continues until b becomes 0
- temp variable: Stores original value of b before updating
- Modulo operation: a % b finds remainder
- Variable swap: a becomes old b, b becomes remainder
- Return value: When b is 0, a contains the GCD
- main(): Reads input and calls gcd function
Visual Explanation
Loading diagram...