efrei/algebre-non-lineaire/euclide_etendu.py

41 lines
814 B
Python
Raw Normal View History

2022-01-17 11:25:27 +01:00
#!/usr/bin/env python3
"""Algorithme d'Euclide étendu
Calcule le PGCD de deux nombres et trouve les coefficients de Bezout.
"""
import sys
2022-01-17 12:45:09 +01:00
def main():
assert len(sys.argv) == 3
a = int(sys.argv[1])
b = int(sys.argv[2])
2022-01-17 11:25:27 +01:00
# Initialisation
2022-01-17 12:45:09 +01:00
r = ["r", a, b]
u = ["u", 1, 0]
v = ["v", 0, 1]
q = ["q", "", a // b]
2022-01-17 11:25:27 +01:00
# Séquence
2022-01-17 12:45:09 +01:00
while True:
r.append(r[-2] % r[-1])
u.append(u[-2] - (q[-1] * u[-1]))
v.append(v[-2] - (q[-1] * v[-1]))
if r[-1] == 0:
q.append("")
break
q.append(r[-2] // r[-1])
print_table(r, u, v, q)
def print_table(r, u, v, q):
"""Représentation de l'algorithme"""
for i in range(len(r)):
print(f"{r[i]:^5} {u[i]:^5} {v[i]:^5} {q[i]:^5}")
if __name__ == "__main__":
main()