GCD and LCM Euclidean Algorithm in DSA Java - Time & Space Complexity
We want to understand how fast the Euclidean algorithm finds the greatest common divisor (GCD) of two numbers.
How does the number of steps grow as the input numbers get bigger?
Analyze the time complexity of the following code snippet.
public int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
This code finds the GCD of two numbers using the Euclidean algorithm by repeatedly replacing the larger number with the remainder.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs repeatedly, performing a modulo operation each time.
- How many times: The loop runs until the remainder becomes zero, which depends on the size of the inputs.
Each step reduces the size of the numbers significantly, so the number of steps grows slowly compared to input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 5 steps |
| 100 | Up to 8 steps |
| 1000 | Up to 11 steps |
Pattern observation: The number of steps grows roughly proportional to the number of digits, not the number itself.
Time Complexity: O(log min(a, b))
This means the steps grow slowly, roughly with the number of digits of the smaller input.
[X] Wrong: "The algorithm takes time proportional to the input numbers themselves."
[OK] Correct: The Euclidean algorithm reduces numbers quickly, so it does not check every number up to the inputs.
Understanding this algorithm's time complexity shows you can analyze efficient number-based algorithms, a useful skill in many coding problems.
"What if we used recursion instead of a loop? How would the time complexity change?"
Practice
a and b?Solution
Step 1: Understand the Euclidean algorithm purpose
The Euclidean algorithm is designed to find the greatest common divisor (GCD) of two integers by repeatedly applying the remainder operation.Step 2: Differentiate GCD from LCM and others
While LCM is related to GCD, the Euclidean algorithm directly computes GCD, not LCM or sums/differences.Final Answer:
The Greatest Common Divisor (GCD) -> Option CQuick Check:
Euclidean algorithm = GCD [OK]
- Confusing GCD with LCM
- Thinking it calculates sum or difference
- Assuming it finds prime factors directly
Solution
Step 1: Check method parameters and return type
The method should take two integers as input and return an integer representing the GCD.Step 2: Validate method signature correctness
public static int gcd(int a, int b) matches this: it is static, returns int, and takes two int parameters. Others have wrong parameters or return type.Final Answer:
public static int gcd(int a, int b) -> Option AQuick Check:
Correct signature = public static int gcd(int a, int b) [OK]
- Adding extra parameters unnecessarily
- Using void return type instead of int
- Omitting static keyword when needed
public class Test {
public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static void main(String[] args) {
System.out.println(gcd(48, 18));
}
}Solution
Step 1: Trace gcd(48, 18) calls
gcd(48,18) calls gcd(18, 48%18=12), then gcd(18,12) calls gcd(12, 18%12=6), then gcd(12,6) calls gcd(6, 12%6=0), returns 6.Step 2: Final return value
When second parameter is 0, return first parameter which is 6.Final Answer:
6 -> Option AQuick Check:
GCD(48,18) = 6 [OK]
- Stopping too early without full recursion
- Mixing up modulo operation
- Returning wrong variable when b=0
public static int lcm(int a, int b) {
return a * b / gcd(a, b);
}
public static int gcd(int a, int b) {
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}Solution
Step 1: Analyze LCM calculation
LCM is calculated as (a * b) / GCD(a, b). If a or b is negative, product can be negative, causing wrong LCM.Step 2: Fix negative product issue
Use Math.abs(a * b) to ensure LCM is always positive.Final Answer:
Use Math.abs(a * b) to avoid negative LCM -> Option DQuick Check:
LCM must be positive; abs fixes sign [OK]
- Ignoring negative inputs causing wrong LCM
- Changing gcd return type incorrectly
- Returning wrong variable in gcd method
nums = {12, 15, 20}, which Java code snippet correctly computes the LCM of all elements using the Euclidean algorithm?Solution
Step 1: Understand LCM of multiple numbers
LCM of multiple numbers can be found by iteratively computing LCM of pairs: lcm(a,b,c) = lcm(lcm(a,b), c).Step 2: Check code correctness
int lcm = nums[0]; for(int i=1; iFinal Answer:
int lcm = nums[0]; for(int i=1; i -> Option BQuick Check:
Iterative LCM with gcd formula works [OK]
- Using gcd instead of lcm in loop
- Summing elements instead of computing LCM
- Starting lcm from 0 causing division errors
Ready to prove it?
Pass the test and this pattern moves unknown
