Skip to content

Commit 2edc2c6

Browse files
Adding new algorithms in here which are very necessary to know!
1 parent 310efd1 commit 2edc2c6

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

maths/basic_maths.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,42 @@
22

33
import math
44

5+
def gcd(a: int, b: int) -> int:
6+
"""Calculate the Greatest Common Divisor (GCD) using Euclid's Algorithm.
7+
>>> gcd(54, 24)
8+
6
9+
>>> gcd(10, 0)
10+
10
11+
>>> gcd(0, 10)
12+
10
13+
>>> gcd(0, 0)
14+
Traceback (most recent call last):
15+
...
16+
ValueError: At least one number must be non-zero
17+
>>> gcd(-54, 24)
18+
6
19+
"""
20+
if a == 0 and b == 0:
21+
raise ValueError("At least one number must be non-zero")
22+
a, b = abs(a), abs(b)
23+
while b:
24+
a, b = b, a % b
25+
return a
26+
27+
28+
def lcm(a: int, b: int) -> int:
29+
"""Calculate the Least Common Multiple (LCM) using GCD.
30+
>>> lcm(12, 15)
31+
60
32+
>>> lcm(0, 10)
33+
0
34+
>>> lcm(-12, 15)
35+
60
36+
"""
37+
if a == 0 or b == 0:
38+
return 0
39+
return abs(a * b) // gcd(a, b)
40+
541

642
def prime_factors(n: int) -> list:
743
"""
@@ -126,3 +162,4 @@ def euler_phi(n: int) -> int:
126162

127163
doctest.testmod()
128164

165+

0 commit comments

Comments
 (0)