Implements the euclidean and extended euclidean division algorithms
This commit is contained in:
parent
c359765855
commit
0ede13a12d
1 changed files with 21 additions and 0 deletions
21
imp/math/numbertheory.py
Normal file
21
imp/math/numbertheory.py
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
def euclidean_algo(a: int, b: int) -> int:
|
||||||
|
while b: a, b = b, a % b
|
||||||
|
return a
|
||||||
|
|
||||||
|
'''
|
||||||
|
Calculates coefficients x and y of Bezout's identity: ax + by = gcd(a,b)
|
||||||
|
NOTE: Based on the Extended Euclidean Algorithm's Wikipedia page
|
||||||
|
'''
|
||||||
|
def extended_euclid_algo(a: int, b: int) -> tuple[int, int]:
|
||||||
|
(old_r, r) = (a, b)
|
||||||
|
(old_s, s) = (1, 0)
|
||||||
|
(old_t, t) = (0, 1)
|
||||||
|
while r != 0:
|
||||||
|
q = old_r // r
|
||||||
|
(old_r, r) = (r, old_r - q*r)
|
||||||
|
(old_s, s) = (s, old_s - q*s)
|
||||||
|
(old_t, t) = (t, old_t - q*t)
|
||||||
|
# Bezout cofficients: (old_s, old_t)
|
||||||
|
# Greatest Common Divisor: old_r
|
||||||
|
# Quotients by the gcd: (t, s)
|
||||||
|
return (t, s)
|
||||||
Loading…
Add table
Add a link
Reference in a new issue