#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <string>
using namespace std;
// Function to calculate the determinant of a 2x2 matrix
double determinant_2x2(const vector<vector<double>>& M) {
return M[0][0] * M[1][1] - M[0][1] * M[1][0];
}
// Function to solve the system using Cramer's Rule
void cramers_rule(const vector<vector<double>>& A, const vector<double>& B) {
int n = 2; // Fixed for 2x2 system
cout << setprecision(6) << fixed;
cout << "--- Cramer's Rule for 2x2 System ---" << endl;
cout << "Coefficients Matrix A:" << endl;
cout << setw(8) << A[0][0] << setw(8) << A[0][1] << endl;
cout << setw(8) << A[1][0] << setw(8) << A[1][1] << endl;
cout << "Constant Vector B:" << endl;
cout << setw(8) << B[0] << endl;
cout << setw(8) << B[1] << endl;
cout << string(40, '-') << endl;
double detA = determinant_2x2(A);
cout << "Output:" << endl;
cout << "Determinant of Matrix A: " << detA << endl;
if (abs(detA) < 1e-9) {
cout << "Matrix is singular; the system is not uniquely solvable." << endl;
return;
}
// Calculate Inverse of A (Optional step in problem, but included for completeness)
double inv_detA = 1.0 / detA;
vector<vector<double>> adjA = {
{A[1][1], -A[0][1]},
{-A[1][0], A[0][0]}
};
cout << "Inverse of Matrix A:" << endl;
cout << setw(8) << adjA[0][0] * inv_detA << setw(8) << adjA[0][1] * inv_detA << endl;
cout << setw(8) << adjA[1][0] * inv_detA << setw(8) << adjA[1][1] * inv_detA << endl;
// 1. Calculate Determinant of Ax1
vector<vector<double>> Ax1 = A;
Ax1[0][0] = B[0];
Ax1[1][0] = B[1];
double detAx1 = determinant_2x2(Ax1);
// 2. Calculate Determinant of Ax2
vector<vector<double>> Ax2 = A;
Ax2[0][1] = B[0];
Ax2[1][1] = B[1];
double detAx2 = determinant_2x2(Ax2);
// Calculate Solutions
double x1 = detAx1 / detA;
double x2 = detAx2 / detA;
cout << "The solution using Cramer's Rule:" << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
cout << string(40, '-') << endl;
}
int main() {
// Sample Input based on the problem statement
vector<vector<double>> A = {
{2.0, 5.0},
{-3.0, 1.0}
};
vector<double> B = {11.0, -4.0};
cramers_rule(A, B);
return 0;
}