Skip to content

Commit

Permalink
Implement Extended Euclidean Algorithm with igcdex function and add c…
Browse files Browse the repository at this point in the history
…orresponding tests

- Introduced a new function `igcdex` in `math_utils.py` to compute the extended greatest common divisor, returning coefficients and the gcd.
- Added unit tests for `igcdex` in `test_math_utils.py` to ensure correctness of the implementation.
- Removed the outdated `sympy` dependency from `requirements.txt` to clean up the requirements.
  • Loading branch information
saleh-mir committed Jan 9, 2025
1 parent 989cb80 commit bc970f0
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
39 changes: 39 additions & 0 deletions jesse/math_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
def igcdex(a, b):
"""Returns x, y, g such that g = x*a + y*b = gcd(a, b).
>>> igcdex(2, 3)
(-1, 1, 1)
>>> igcdex(10, 12)
(-1, 1, 2)
>>> x, y, g = igcdex(100, 2004)
>>> x, y, g
(-20, 1, 4)
>>> x*100 + y*2004
4
"""
if (not a) and (not b):
return (0, 1, 0)

if not a:
return (0, b // abs(b), abs(b))
if not b:
return (a // abs(a), 0, abs(a))

if a < 0:
a, x_sign = -a, -1
else:
x_sign = 1

if b < 0:
b, y_sign = -b, -1
else:
y_sign = 1

x, y, r, s = 1, 0, 0, 1

while b:
(c, q) = (a % b, a // b)
(a, b, r, s, x, y) = (b, c, x - q * r, y - q * s, r, s)

return (x * x_sign, y * y_sign, a)
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,4 @@ aiofiles~=0.7.0
numba~=0.61.0rc2
PyJWT~=2.8.0
cryptography~=42.0.5
sympy~=1.6
ecdsa>=0.16.0
6 changes: 6 additions & 0 deletions tests/test_math_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import jesse.math_utils as mu


def test_igcdex():
assert mu.igcdex(2, 3) == (-1, 1, 1)
assert mu.igcdex(10, 12) == (-1, 1, 2)

0 comments on commit bc970f0

Please sign in to comment.