solution_comparison/euclid.py

31 lines
787 B
Python

import sys, re
def gcd(a, b):
if b == 0:
return 1, 0, a
x, y, d = gcd(b, a % b)
x = y
y = (d - x*a) // b
return x, y, d
def solve(task):
f = re.fullmatch(r'(\d+)x=(\d+)mod(\d+)', task)
if f == None:
return "Usage Example: py euclid.py '7x=8mod13'"
a, b, m = int(f.groups()[0]), int(f.groups()[1]), int(f.groups()[2])
d = gcd(a, m)[2]
if d > 1 and b % d != 0:
return 'No solutions'
a1, b1, m1 = a // d, b // d, m // d
u, _, _ = gcd(a1, m1)
x0 = b1*u
s = ""
for i in range(0, d):
s += f'x={(x0+m//d*i)%m}mod{m}\n'
return s[:-1]
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage Example: py euclid.py '7x=8mod13'")
sys.exit(1)
print(solve(sys.argv[1]))