MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / extended_gcd

Function extended_gcd

maths/modular_division.py:82–109  ·  view source on GitHub ↗

Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) ** extended_gcd function is used when d = gcd(a,b) is required in output

(a: int, b: int)

Source from the content-addressed store, hash-verified

80
81
82def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
83 """
84 Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x
85 and y, then d = gcd(a,b)
86 >>> extended_gcd(10, 6)
87 (2, -1, 2)
88
89 >>> extended_gcd(7, 5)
90 (1, -2, 3)
91
92 ** extended_gcd function is used when d = gcd(a,b) is required in output
93
94 """
95 assert a >= 0
96 assert b >= 0
97
98 if b == 0:
99 d, x, y = a, 1, 0
100 else:
101 (d, p, q) = extended_gcd(b, a % b)
102 x = q
103 y = p - q * (a // b)
104
105 assert a % d == 0
106 assert b % d == 0
107 assert d == a * x + b * y
108
109 return (d, x, y)
110
111
112def extended_euclid(a: int, b: int) -> tuple[int, int]:

Callers 1

modular_divisionFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected