efrei/algebre-non-lineaire/euclide_etendu.py

58 lines
1.1 KiB
Python
Executable file

#!/usr/bin/env python3
"""Algorithme d'Euclide étendu
Calcule le PGCD de deux nombres et trouve les coefficients de Bezout.
"""
import sys
def main():
if len(sys.argv) == 3:
a = int(sys.argv[1])
b = int(sys.argv[2])
else:
a = int(input("a : "))
b = int(input("b : "))
calculate(a, b)
def calculate(a, b):
if b > a:
a, b = b, a
# Initialisation
r = ["r", a, b]
u = ["u", 1, 0]
v = ["v", 0, 1]
q = ["q", "", a // b]
# Séquence
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)
print("Le PGCD est", r[-2])
return u[-1]
def print_table(r, u, v, q):
"""Représentation de l'algorithme"""
width = max((len(str(i)) for i in r))
for i in range(len(r)):
print(f"{r[i]:^{width}} {u[i]:^{width}} {v[i]:^{width}} {q[i]:^{width}}")
if __name__ == "__main__":
main()