Acwing---878. Linear Congruence Equation (Java)_Mathematics_Expanded Euclidean Algorithm Template

Original title link

①. Title

Insert picture description here

②. Thinking

Insert picture description here

  • First use the extended Euclidean algorithm to find a set of integers x', y'such that a∗x'+m∗y'=gcd(a,m). Then x=x'∗b/gcd(a,m)%mthat is being solved.
  • a * x ≡ b (mod m) is transformed into an extended Euclidean form: a * x + b * y = gcd(a, b)
  • The original formula becomes: a * x = m * y + b (Note: mod m is b, then the result is the sum of multiples of m and b)
  • a * x - m * y = b
  • Another y1 = -y is: a * x + m * y1 = b
  • According to the extended Euclid theorem,只要 b 是 gcd(a, m)的倍数即有解!
  • On the other hand, d = gcd(a, m), the formula we get is actually: a * x + m * y1 = gcd(a, m) = d (Note; the above b is actually a multiple of d)
  • So multiplying b / d on the left and right can be transformed into:a * x * b / d + m * y1 * b / d = b * b / d = b
  • That is, the final answer is:res = x * d / b % m

③. Learning points

转换成扩展欧几里得公式,进行模板套用

④. Code implementation

import java.util.Scanner;

public class Main {
    
    
	static int x,y;
	//扩展欧几里得模板  a * x + b * y = gcd(a, b) 
	static int exgcd(int a,int b) {
    
    
		if(b==0) {
    
    
			x=1;
			y=0;
			return a;
		}
		int d=exgcd(b,a%b);
		int tmp=x;
		x=y;
		y=tmp-a/b*y;
		return d;
	}
	
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		while(n-->0) {
    
    
			int a=sc.nextInt();
			int b=sc.nextInt();
			int m=sc.nextInt();
			int d=exgcd(a, m);
			//只要 b 是 gcd(a, m)的倍数即有解
			if(b%d==0) {
    
    
			    // x′=x0∗c/d
				long res=(long)x*b/d%m;
				System.out.println(res);
			}else {
    
    
				System.out.println("impossible");
			}
		}
	}

}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45480785/article/details/113896367