Last active
May 9, 2025 12:50
-
-
Save mydreambei-ai/e24e610556c51a7ca8460ebffccf4287 to your computer and use it in GitHub Desktop.
Extended Euclidean algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def extend_gcd(a, b): | |
if a < b: | |
a, b = b, a | |
r = np.array([[1, 0], [0, 1]]) | |
while 1: | |
quotient, remainder = divmod(a, b) | |
# r = a - quotient * b | |
# np.array([a,b]) @ np.array([0, 1]) = b; 相当于a = b | |
# | |
# np.array([a,b]) @ np.array([1, -quotient]) = r; 相当于 b = r | |
# 递归计算quotient | |
# np.array([a, b]) @ np.array([[0, 1],[1, -quotient_1]]) @ np.array([[0, 1], [1, -quotient_2]]) @ .... | |
# | |
# | |
r = r @ np.array([[0, 1],[1, -quotient]]) | |
if remainder == 1: | |
return r[:, 1] | |
if remainder == 0: | |
raise ValueError(f"input has factor {b}") | |
a = b | |
b = remainder |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment