/*
Name:Pritom Sharma
Id: 230241008
Report:Crsmers Rule Method
*/
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
double determinant(vector<vector<double>> mat, int n) {
double det = 0;
if (n == 1) {
return mat[0][0];
}
vector<vector<double>> temp(n - 1, vector<double>(n - 1));
int sign = 1;
for (int f = 0; f < n; f++) {
int i = 0, j = 0;
for (int row = 1; row < n; row++) {
for (int col = 0; col < n; col++) {
if (col != f) {
temp[i][j++] = mat[row][col];
if (j == n - 1) {
j = 0;
i++;
}
}
}
}
det += sign * mat[0][f] * determinant(temp, n - 1);
sign = -sign;
}
return det;
}
void cramersRule() {
int n;
cout << "Enter the order of square matrix: ";
cin >> n;
vector<vector<double>> A(n, vector<double>(n));
vector<double> B(n), X(n);
cout << "Enter coefficients of matrix A:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
cout << "Enter constants of vector B: ";
for (int i = 0; i < n; i++) {
cin >> B[i];
}
double detA = determinant(A, n);
cout << "\nDeterminant of A: " << fixed << setprecision(3) << detA << endl;
if (detA == 0) {
cout << "Matrix is singular; the system is not uniquely solvable.\n";
return;
}
vector<vector<double>> invA(n, vector<double>(n));
if (n == 2) {
invA[0][0] = A[1][1] / detA;
invA[0][1] = -A[0][1] / detA;
invA[1][0] = -A[1][0] / detA;
invA[1][1] = A[0][0] / detA;
cout << "\nInverse of matrix A:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << fixed << setprecision(4) << invA[i][j] << "\t";
}
cout << endl;
}
}
vector<vector<double>> temp = A;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
temp[j][i] = B[j];
}
X[i] = determinant(temp, n) / detA;
temp = A; // Reset temp matrix
}
cout << "\nThe solution using Cramer's Rule:\n";
for (int i = 0; i < n; i++) {
cout << "x" << i + 1 << " = " << fixed << setprecision(6) << X[i] << endl;
}
}
int main() {
cramersRule();
return 0;
}