Created
September 26, 2014 22:31
-
-
Save stopfaner/b57c5c94ff5f77fbe919 to your computer and use it in GitHub Desktop.
Determinant of matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <conio.h> | |
int getDet(int, int**); | |
int countMinor(int **); | |
int** getMinor(int**, int, int, int); | |
using namespace std; | |
int power(int n) { | |
return n%2==0?1:-1; | |
} | |
int main() { | |
int size; | |
cin>>size; | |
int** array = (int**)malloc(size*sizeof(int)); | |
for(int i = 0; i<size;i++) { | |
array[i] = (int*)malloc(sizeof(int) * size); | |
for(int j=0;j<size;j++) | |
{ | |
cin>>array[i][j]; | |
} | |
} | |
int** temp = getMinor(array, size, 0, 0); | |
for(int i = 0;i<3;i++) | |
{ | |
for(int j=0;j<3;j++) | |
cout<<temp[i][j]<<" "; | |
cout<<endl; | |
} | |
cout<<getDet(size, array); | |
free(array); | |
getch(); | |
return 0; | |
} | |
int getDet(int size, int** mMat) { | |
int col = 0; | |
int det = 0; | |
if(size > 3) { | |
for(int i = 0; i<size; i++) { | |
det += power(i) * mMat[col][i] * getDet(size-1, getMinor(mMat, size, col, i)) ; | |
} | |
return det; | |
} | |
else | |
return countMinor(mMat); | |
} | |
int countMinor(int** mat) { | |
return ((mat[0][0] * mat[1][1] * mat[2][2]) + | |
(mat[0][1] * mat[1][2] * mat[2][0]) + | |
(mat[1][0] * mat[2][1] * mat[0][2]) - | |
(mat[0][2] * mat[1][1] * mat[2][0]) - | |
(mat[0][1] * mat[1][0] * mat[2][2]) - | |
(mat[0][0] * mat[1][2] * mat[2][1])); | |
} | |
int** getMinor(int** matrix, int size, int n, int k) { | |
//matrix = (int** )malloc(sizeof(int) * size); | |
int** temp = (int** )malloc(sizeof(int) * size); | |
for(int i = 0, z = 0; i < size , z<size; i++, z++) { | |
if(i==n) | |
z++; | |
temp[i] = (int* )malloc(sizeof(int) * size); | |
for(int j = 0, p = 0; j < size, p<size; j++, p++) { | |
if( j==k) | |
p++; | |
temp[i][j] = matrix[z][p]; | |
} | |
} | |
return temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment