-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgcd_lcm.py
More file actions
98 lines (71 loc) · 2.02 KB
/
gcd_lcm.py
File metadata and controls
98 lines (71 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""
Greatest Common Divisor (GCD) and Least Common Multiple (LCM)
GCD: The largest positive integer that divides both numbers without remainder.
LCM: The smallest positive integer that is divisible by both numbers.
Euclidean Algorithm is used for efficient GCD computation.
Time Complexity: O(log(min(a, b)))
Space Complexity: O(1)
"""
def gcd_euclidean(a, b):
"""
Computes GCD using Euclidean algorithm (iterative).
Args:
a: First integer
b: Second integer
Returns:
GCD of a and b
"""
while b:
a, b = b, a % b
return abs(a)
def gcd_recursive(a, b):
"""
Computes GCD using Euclidean algorithm (recursive).
Args:
a: First integer
b: Second integer
Returns:
GCD of a and b
"""
if b == 0:
return abs(a)
return gcd_recursive(b, a % b)
def lcm(a, b):
"""
Computes LCM using the relationship: LCM(a, b) = |a * b| / GCD(a, b)
Args:
a: First integer
b: Second integer
Returns:
LCM of a and b
"""
if a == 0 or b == 0:
return 0
return abs(a * b) // gcd_euclidean(a, b)
def extended_gcd(a, b):
"""
Extended Euclidean Algorithm: finds GCD and coefficients x, y such that
ax + by = gcd(a, b)
Args:
a: First integer
b: Second integer
Returns:
Tuple (gcd, x, y) where gcd is GCD and ax + by = gcd
"""
if a == 0:
return abs(b), 0, 1 if b >= 0 else -1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
# Example usage
if __name__ == "__main__":
a, b = 48, 18
print(f"GCD({a}, {b}):")
print(f" Euclidean (iterative): {gcd_euclidean(a, b)}")
print(f" Euclidean (recursive): {gcd_recursive(a, b)}")
print(f"\nLCM({a}, {b}): {lcm(a, b)}")
print(f"\nExtended GCD({a}, {b}):")
gcd, x, y = extended_gcd(a, b)
print(f" GCD: {gcd}")
print(f" Coefficients: {a}*{x} + {b}*{y} = {gcd}")