Find GCD (Greatest Common Divisor)
C++
Hard
2 views
Problem Description
Find largest number that divides both numbers completely.
Example: GCD of 12 and 18 is 6
Real Life: Used when simplifying fractions.
Step-by-Step Logic:
1. Take two numbers
2. Find smaller of two numbers
3. Start from smaller and go down to 1
4. First number that divides both is GCD
5. Print GCD
Official Solution
void control_q11_gcd() {
int num1 = 48;
int num2 = 18;
int gcd = 1;
int smaller = (num1 < num2) ? num1 : num2;
for(int i = smaller; i >= 1; i--) {
if(num1 % i == 0 && num2 % i == 0) {
gcd = i;
break; // Found GCD, stop searching
}
}
cout << "GCD of " << num1 << " and " << num2 << " is: " << gcd << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!