Challenge - 5 Problems
Euclidean Algorithm Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Euclidean GCD function
What is the output of this C++ code that calculates the GCD of 48 and 18 using the Euclidean algorithm?
DSA C++
int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } int main() { int result = gcd(48, 18); std::cout << result << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember the Euclidean algorithm repeatedly replaces the larger number by the remainder until the remainder is zero.
✗ Incorrect
The GCD of 48 and 18 is 6 because 6 is the largest number that divides both without remainder. The Euclidean algorithm finds this by repeated modulo operations.
❓ Predict Output
intermediateLCM calculation using GCD
What is the output of this C++ code that calculates the LCM of 21 and 6 using the GCD function?
DSA C++
int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } int lcm(int a, int b) { return (a / gcd(a, b)) * b; } int main() { int result = lcm(21, 6); std::cout << result << std::endl; return 0; }
Attempts:
2 left
💡 Hint
LCM can be found by dividing the product of the two numbers by their GCD.
✗ Incorrect
The GCD of 21 and 6 is 3. LCM = (21 / 3) * 6 = 7 * 6 = 42.
🧠 Conceptual
advancedWhy Euclidean Algorithm is efficient for GCD?
Why is the Euclidean algorithm considered efficient for finding the GCD of two numbers?
Attempts:
2 left
💡 Hint
Think about how the remainder changes in each step.
✗ Incorrect
The Euclidean algorithm reduces the size of the numbers quickly by replacing the larger number with the remainder, which is always smaller, leading to fast convergence.
❓ Predict Output
advancedOutput of recursive GCD function with negative input
What is the output of this C++ code that calculates the GCD of -56 and 98 using a recursive Euclidean algorithm?
DSA C++
int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int result = gcd(-56, 98); std::cout << result << std::endl; return 0; }
Attempts:
2 left
💡 Hint
The modulo operator in C++ can return negative values when the dividend is negative.
✗ Incorrect
The recursive function returns the GCD but does not handle negative inputs explicitly, so the result keeps the sign of the first argument, which is -14.
🔧 Debug
expertIdentify the error in this LCM calculation code
What error will this C++ code produce when calculating the LCM of 15 and 20?
DSA C++
int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int lcm(int a, int b) { return a * b / gcd(a, b); } int main() { int result = lcm(15, 20); std::cout << result << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Check if the multiplication a * b can overflow for these inputs.
✗ Incorrect
For inputs 15 and 20, a * b = 300 fits in int range, so no overflow occurs. The output is correct: 60.
