// Extended Euclidean Algorithm.// Finds integers x, y such that a*x + b*y = gcd(a, b),// and returns gcd(a, b).intex_gcd(inta,intb,int&x,int&y){if(!b){x=1;y=0;returna;}else{intd=ex_gcd(b,a%b,y,x);y-=a/b*x;returnd;}}// 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.intsolve_linear_congruence_equation(inta,intb,intn){intx,y;intd=ex_gcd(a,n,x,y);if(b%d)return-1;n/=d;x*=b/d;return(x%n+n)%n;}
defex_gcd(a,b):""" Extended Euclidean Algorithm. Finds integers x, y such that a*x + b*y = gcd(a, b), and returns (gcd, x, y). """ifb==0:returna,1,0d,x1,y1=ex_gcd(b,a%b)x=y1y=x1-(a//b)*y1returnd,x,ydefsolve_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)ifb%d!=0:return-1n//=dx*=b//dreturn(x%n+n)%n