877. Linear Congruence Equation
Original title link
①. Title
![Insert picture description here](https://img-blog.csdnimg.cn/20210221090441877.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTQ4MDc4NQ==,size_16,color_FFFFFF,t_70)
②. Thinking
![Insert picture description here](https://img-blog.csdnimg.cn/20210221090748839.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTQ4MDc4NQ==,size_16,color_FFFFFF,t_70)
- 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)%m
that 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;
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);
if(b%d==0) {
long res=(long)x*b/d%m;
System.out.println(res);
}else {
System.out.println("impossible");
}
}
}
}
![Insert picture description here](https://img-blog.csdnimg.cn/20210221091539643.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTQ4MDc4NQ==,size_16,color_FFFFFF,t_70)