Problem
Compute determinant
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Compute determinant
Created Data : 12-06-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
using namespace std;
void PrintSquareMatrix(int* m, int s)
{
for(int i = 0; i < s * s; ++i){
cout << setw(4) << m[i];
if((i + 1) % s == 0){
cout << endl;
}
}
}
int ComputeDeterminant(int* m, int s)
{
if(s == 1){
return m[0];
}
int ret = 0;
int* subm = new int[(s-1) * (s - 1)];
int sign = -1;
for(int i = 0; i < s; ++i){
int* p = subm;
for(int k = 1; k < s; k++){
for(int j = 0; j < i; j++){
*p ++ = m[k * s + j];
}
for(int j = i + 1; j < s; j++){
*p ++ = m[k * s + j];
}
}
sign *= -1;
ret += sign * m[i] * ComputeDeterminant(subm, s - 1);
}
delete[] subm;
return ret;
}
int main(int argc, char* argv[])
{
srand(5);
for(int s = 1; s < 5; s++){
int* m = new int[s * s];
for(int i = 0; i < s * s; ++i){
m[i] = rand() % 8;
}
cout << "The square matrix is " << endl;
PrintSquareMatrix(m, s);
cout << "The determinant of matrix is ";
cout << ComputeDeterminant(m, s) << endl << endl;
delete[] m;
}
return 0;
}
Output
The square matrix is
6
The determinant of matrix is 6
The square matrix is
5 7
1 4
The determinant of matrix is 13
The square matrix is
6 7 1
0 0 2
1 5 4
The determinant of matrix is -46
The square matrix is
2 3 3 3
6 7 5 0
1 3 0 1
0 3 2 3
The determinant of matrix is -73
Press any key to continue . . .