AcWing 1299. 五指山
原题链接
简单
作者:
不知名的fE
,
2024-11-25 15:15:47
,
所有人可见
,
阅读 1
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- > 0) {
long n = sc.nextLong(), d = sc.nextLong(), x = sc.nextLong(), y = sc.nextLong();
long[] a = new long[1];
long[] b = new long[1];
long gcd = exgcd(n, d, a, b);
if((y - x) % gcd != 0) {
System.out.println("Impossible");
}else {
b[0] *= (y - x) / gcd;
n /= gcd;
System.out.println((b[0] % n + n) % n);
}
}
sc.close();
}
private static long exgcd(long a, long b, long[] x, long[] y) {
if(b == 0) {
x[0] = 1;
y[0] = 0;
return a;
}
long d = exgcd(b, a % b, y, x);
y[0] -= a / b * x[0];
return d;
}
}