Answer the question
In order to leave comments, you need to log in
How to handle all cases when solving a system of linear equations with two unknowns?
Good day to all.
I'm sorry for my somewhat stupid question, but I had a problem preparing for the olympiad. Specifically, there are problems with this problem about a system of equations with two unknowns.
I'm deaf on the 34th test.
It would seem that everything is simple:
Case 1 (coefficients of the variables are disproportionate) Here the system has a unique solution.
Case 2 (coefficients of variables are proportional):
This case is divided into two:
a) coefficients of variables and free terms are proportional
b) coefficients of variables and free terms are proportional There are simply no solutions, since the lines are parallel.
I consider case a) in more detail, since it is required to display different values based on possible pairs (x, y).
1. All coefficients of the variables are 0 and the free terms are 0 - an infinite number of solutions
2. All coefficients of the variables are 0, but one of the free terms is not equal to 0 - there are no solutions
3. When the coefficients of X are 0 - then y we have a unique solution for Y, and X can be any
4. When the coefficients for Y are 0 - then we have a unique solution for X, and Y can be any
5. Non-zero coefficients, then we have a solution in the form Y = k * X + B
I implemented all this in C ++, the code is presented below:
int main() {
double a, b, c, d, e, f;
double x, y;
const int no_roots = 0;
const int kx_roots = 1;
const int one_xy_root = 2;
const int one_x = 3;
const int one_y = 4;
const int inf_roots = 5;
cin >> a >> b >> c >> d >> e >> f;
double det = a * d - b * c;
double det_x = (e * d - b * f);
double det_y = (a * f - e * c);
bool x_null = a == 0 && c == 0;
bool y_null = b == 0 && d == 0;
if (det != 0) {
x = det_x / det;
y = det_y / det;
cout << one_xy_root << ' ' << x << ' ' << y;
}
else {
if (det_x == 0 && det_y == 0) {
if (x_null && y_null) {
if (e != 0 || f != 0) {
cout << no_roots;
}
else {
cout << inf_roots;
}
}
else if (x_null) {
if (b != 0) {
y = e / b;
}
else {
y = f / d;
}
cout << one_y << ' ' << y;
}
else if (y_null) {
if (a != 0) {
x = e / a;
}
else {
x = f / a;
}
cout << one_x << ' ' << x;
}
else {
double bi, k;
if (b != 0) {
bi = e / b;
k = -a / b;
}
else {
bi = f / d;
k = -c / d;
}
cout << kx_roots << ' ' << k << ' ' << bi;
}
}
else {
cout << no_roots;
}
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
To solve systems, it is more convenient to use matrices, and Cramer's method in particular. It's not as scary as it looks. And the code will turn out much simpler and more logical.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question