// Extended Euclidean Algorithm.// Finds integers x, y such that a*x + b*y = gcd(a, b),// and returns gcd(a, b).int ex_gcd(int a, int b, int& x, int& y) { if (!b) { x = 1; y = 0; return a; } else { int d = ex_gcd(b, a % b, y, x); y -= a / b * x; return d; }}// Solves the linear congruence equation:// a * x ≡ b (mod n), where n > 0.// Returns the smallest non-negative solution x,// or -1 if there is no solution.int solve_linear_congruence_equation(int a, int b, int n) { int x, y; int d = ex_gcd(a, n, x, y); if (b % d) return -1; n /= d; return ((long long)x * (b / d) % n + n) % n;}
Python
def ex_gcd(a, b): """ Extended Euclidean Algorithm. Finds integers x, y such that a*x + b*y = gcd(a, b), and returns (gcd, x, y). """ if b == 0: return a, 1, 0 d, x1, y1 = ex_gcd(b, a % b) x = y1 y = x1 - (a // b) * y1 return d, x, ydef solve_linear_congruence_equation(a, b, n): """ Solves the linear congruence equation: a * x ≡ b (mod n), where n > 0. Returns the smallest non-negative solution x, or -1 if there is no solution. """ d, x, y = ex_gcd(a, n) if b % d != 0: return -1 n //= d return (x * (b // d) % n + n) % n