题目描述
给定一个二元一次方程组,形如:
a * x + b * y = c;
d * x + e * y = f;
x,y代表未知数,a, b, c, d, e, f为参数。
求解x,y
输入
输入描述:
输入包含六个整数: a, b, c, d, e, f;
输入样例:
例:
3 7 41 2 1 9
输出
输出描述:
输出为方程组的解,两个整数x, y。
输出样例:
例:
2 5
HINT:时间限制:1.0s 内存限制:256.0MB
0 <= a, b, c, d, e, f <= 2147483647
解题思路
可以先求出系数的最小公倍数,然后通过消未知数来计算结果。
代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int a, b, c, d, e, f;
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
d = sc.nextInt();
e = sc.nextInt();
f = sc.nextInt();
int lcm = a * d / gcd(a, d);// 最小公倍数
int a1 = lcm / a;
int d1 = lcm / d;
int y = (c * a1 - f * d1) / (b * a1 - e * d1);
int x = (c - b * y) / a;
System.out.println(x + " " + y);
}
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
}