def gauss(a1, m1, a2, m2): # Return x such that x = a1 mod m1, x = a2 mod m2 (-1 if no solution) # Pre: a1, a2, m1, m2 >= 0 # Post: x = a1 mod m1, x = a2 mod m2, 0 <= x < lcm(m1, m2) (x = -1 if no solution) d = gcd(m1, m2) if a1 % d != a2 % d: return -1 if a1 > a2: a1, m1, a2, m2 = a2, m2, a1, m1 t1 = lin_solve(m1//d, (a2-a1)//d % (m2//d), m2//d) # See Bach-Shallit p.116 return (a1 + t1 * m1) % lcm(m1, m2)
def lin_solve(a, b, n): # Solve a x = b mod n (-1 if no solution) # Pre: a, b, n >= 0 # Post: a x = b mod n, 0 <= x < n (x = -1 if no solution) g = gcd(a,n) if g != 1: return -1 a_inv = inverse(a, n) if a_inv == 0: return -1 return (a_inv * b) % n
def LCM(a, b): from GCD import gcd return a * b / gcd(a, b)