GCD and LCM Algorithms
Understanding GCD and LCM
Greatest Common Divisor (GCD)
The Greatest Common Divisor (GCD) is the largest positive integer that divides each of the given numbers without a remainder.
Euclidean Algorithm Implementation
def gcd(a, b):
while b:
a, b = b, a % b
return a
## Example usage
print(gcd(48, 18)) ## Output: 6
Recursive GCD Implementation
def gcd_recursive(a, b):
if b == 0:
return a
return gcd_recursive(b, a % b)
## Example usage
print(gcd_recursive(48, 18)) ## Output: 6
Least Common Multiple (LCM)
The Least Common Multiple (LCM) is the smallest positive integer that is divisible by each of the given numbers.
LCM Calculation Using GCD
def lcm(a, b):
return abs(a * b) // gcd(a, b)
## Example usage
print(lcm(4, 6)) ## Output: 12
Algorithm Visualization
graph TD
A[Start] --> B{Input Numbers}
B --> C[Calculate GCD]
C --> D[Calculate LCM]
D --> E[Return Result]
Advanced GCD and LCM Techniques
Multiple Numbers GCD
def gcd_multiple(numbers):
result = numbers[0]
for num in numbers[1:]:
result = gcd(result, num)
return result
## Example usage
print(gcd_multiple([48, 18, 12])) ## Output: 6
Multiple Numbers LCM
def lcm_multiple(numbers):
result = numbers[0]
for num in numbers[1:]:
result = lcm(result, num)
return result
## Example usage
print(lcm_multiple([4, 6, 8])) ## Output: 24
Algorithm |
Time Complexity |
Space Complexity |
Euclidean |
O(log(min(a,b))) |
O(1) |
Recursive |
O(log(min(a,b))) |
O(log(min(a,b))) |
Practical Applications
- Fraction simplification
- Cryptography
- Computer graphics
- Scheduling algorithms
Complex GCD Calculation
def extended_gcd(a, b):
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
## Example usage
gcd, x, y = extended_gcd(48, 18)
print(f"GCD: {gcd}, Coefficients: {x}, {y}")
By mastering these GCD and LCM algorithms, you'll enhance your problem-solving skills in Python. LabEx recommends practicing these techniques to improve your algorithmic thinking.