Pagini recente » Cod sursa (job #1566722) | Cod sursa (job #1667119) | Cod sursa (job #3189674) | Cod sursa (job #1367806) | Cod sursa (job #3132339)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("input.txt");
ofstream cout("output.txt");
// Function to calculate the determinant of a matrix
void performLUDecomposition(const vector<vector<double>>& matrix, vector<vector<double>>& lower, vector<vector<double>>& upper) {
int n = matrix.size();
lower.resize(n, vector<double>(n, 0.0));
upper.resize(n, vector<double>(n, 0.0));
for (int i = 0; i < n; i++) {
lower[i][i] = 1.0;
for (int j = i; j < n; j++) {
double sum = 0.0;
for (int k = 0; k < i; k++) {
sum += lower[i][k] * upper[k][j];
}
upper[i][j] = matrix[i][j] - sum;
}
for (int j = i + 1; j < n; j++) {
double sum = 0.0;
for (int k = 0; k < i; k++) {
sum += lower[j][k] * upper[k][i];
}
lower[j][i] = (matrix[j][i] - sum) / upper[i][i];
}
}
}
// Calculate the determinant using LU decomposition
double calculateDeterminant(const vector<vector<double>>& matrix) {
int n = matrix.size();
// Perform LU decomposition
vector<vector<double>> lower, upper;
performLUDecomposition(matrix, lower, upper);
// Calculate determinant from the upper triangular matrix
double determinant = 1.0;
for (int i = 0; i < n; i++) {
determinant *= upper[i][i];
}
return determinant;
}
int main() {
int size;
cin >> size;
// Create a vector to hold the matrix
vector<vector<double>> matrix(size, vector<double>(size));
// Read the matrix elements from the keyboard
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cin >> matrix[i][j];
}
}
double determinant = calculateDeterminant(matrix);
cout << determinant << endl;
return 0;
}