例题1:扩展欧几里得算法
给定 n 对正整数 ai,bi,对于每对数,求出一组 xi,yi,使其满足
输入格式
第一行包含整数 n。
接下来 n 行,每行包含两个整数 ai,bi。
输出格式
输出共 n 行,对于每组 ai,bi,求出一组满足条件的 xi,yi,每组结果占一行。
本题答案不唯一,输出任意满足条件的 xi,yi 均可。
数据范围
1≤n≤
1
0
5
10^5
105,
1≤ai,bi≤2×
1
0
9
10^9
109
输入样例:
2
4 6
8 18
输出样例:
-1 1
-2 1
答案:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static int exgcd(int a, int b, int[] x, int[] y) {
if (b == 0) {
x[0] = 1;
y[0] = 0;
return a;
} else {
int d = exgcd(b, Math.floorMod(a, b), y, x);
y[0] -= a / b * x[0];
return d;
}
}
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
//裴蜀定理
String[] str = bufferedReader.readLine().split(" ");
int n = Integer.parseInt(str[0]);
for (int i = 0; i < n; i++) {
str = bufferedReader.readLine().split(" ");
int[] x = new int[1];
int[] y = new int[1];
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
exgcd(a, b, x, y);
System.out.println(x[0] + " " + y[0]);
}
}
}
例题2:线性同余方程
给定 n 组数据 ai,bi,mi,对于每组数求出一个 xi,使其满足 ai × xi≡bi(mod mi),如果无解则输出 impossible
。
输入格式
第一行包含整数 n。
接下来 n 行,每行包含一组数据 ai,bi,mi。
输出格式
输出共 n 行,每组数据输出一个整数表示一个满足条件的 xi,如果无解则输出 impossible
。
每组数据结果占一行,结果可能不唯一,输出任意一个满足条件的结果均可。
输出答案必须在 int 范围之内。
数据范围
1≤n≤
1
0
5
10^5
105,
1≤ai,bi,mi≤2×
1
0
9
10^9
109
输入样例:
2
2 3 6
4 3 5
输出样例:
impossible
-3
答案:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static int exgcd(int a, int b, int[] x, int[] y) {
if (b == 0) {
x[0] = 1;
y[0] = 0;
return a;
} else {
int d = exgcd(b, Math.floorMod(a, b), y, x);
y[0] -= a / b * x[0];
return d;
}
}
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
//a * x = m * y + b 等价于 a * x + m * y` = b 等价于 a * x + m * y = b
String[] str = bufferedReader.readLine().split(" ");
int n = Integer.parseInt(str[0]);
for (int i = 0; i < n; i++) {
str = bufferedReader.readLine().split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
int m = Integer.parseInt(str[2]);
int[] x = new int[1];
int[] y = new int[1];
int d = exgcd(a, m, x, y);
if (b % d == 0) {
System.out.println((long) x[0] * (b / d) % m);
} else {
System.out.println("impossible");
}
}
}
}