-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcm.py
More file actions
26 lines (18 loc) · 703 Bytes
/
lcm.py
File metadata and controls
26 lines (18 loc) · 703 Bytes
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
"""An implementation of finding the least common multiple of two number - ~O(log(a + b))."""
class LCM:
"""Class for finding the least common multiple."""
def _gcd(self, a: int, b: int) -> int:
"""Computes the greatest common divisor of a & b."""
return abs(a) if not b else self._gcd(b, a % b)
def lcm(self, a: int, b: int) -> int:
"""Computes the least common multiple of a & b."""
lcm = (a // self._gcd(a, b)) * b
return abs(lcm)
def main() -> None:
lcm = LCM()
print(lcm.lcm(12, 18)) # 36
print(lcm.lcm(-12, 18)) # 36
print(lcm.lcm(12, -18)) # 36
print(lcm.lcm(-12, -18)) # 36
if __name__ == '__main__':
main()