Skip to content

Instantly share code, notes, and snippets.

@ihower
Created November 30, 2010 15:10
Show Gist options
  • Save ihower/721803 to your computer and use it in GitHub Desktop.
Save ihower/721803 to your computer and use it in GitHub Desktop.
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int n, i, j, ii, jj, row, col, result=0;
int a[100][100];
int b[10][10];
printf("Input N = ");
scanf("%d",&n);
for(i=0; i < n ; i++) {
for (j=0; j < n; j++) {
printf("Input a%d,%d = ", i+1, j+1);
scanf("%d",&a[i][j]);
}
}
if ( n == 1 ) result = a[0][0];
if ( n == 2 ) result = a[0][0]*a[1][1] - a[0][1]*a[1][0];
if ( n == 3 ) result = a[0][0]*a[1][1]*a[2][2] + a[0][1]*a[1][2]*a[2][0] + a[0][2]*a[1][0]*a[2][1] - a[0][2]*a[1][1]*a[2][0] - a[0][0]*a[1][2]*a[2][1] - a[0][1]*a[1][0]*a[2][2];
if ( n == 4 ) {
// make subdet A0,0
row=0; col=0;
ii=0, jj=0;
for( i=0; i<n; i++) {
if (i == row) continue;
for ( j=0; j<n; j++) {
if (j == col) continue;
b[ii][jj] = a[i][j];
jj++;
}
ii++; jj=0;
}
result += a[0][0] * ( b[0][0]*b[1][1]*b[2][2] + b[0][1]*b[1][2]*b[2][0] + b[0][2]*b[1][0]*b[2][1] - b[0][2]*b[1][1]*b[2][0] - b[0][0]*b[1][2]*b[2][1] - b[0][1]*b[1][0]*b[2][2] );
// make subdet A1,0
row=1; col=0;
ii=0, jj=0;
for( i=0; i<n; i++) {
if (i == row) continue;
for ( j=0; j<n; j++) {
if (j == col) continue;
b[ii][jj] = a[i][j];
jj++;
}
ii++; jj=0;
}
result -= a[1][0] * ( b[0][0]*b[1][1]*b[2][2] + b[0][1]*b[1][2]*b[2][0] + b[0][2]*b[1][0]*b[2][1] - b[0][2]*b[1][1]*b[2][0] - b[0][0]*b[1][2]*b[2][1] - b[0][1]*b[1][0]*b[2][2] );
// make subdet A2,0
row=2; col=0;
ii=0, jj=0;
for( i=0; i<n; i++) {
if (i == row) continue;
for ( j=0; j<n; j++) {
if (j == col) continue;
b[ii][jj] = a[i][j];
jj++;
}
ii++; jj=0;
}
result += a[2][0] * ( b[0][0]*b[1][1]*b[2][2] + b[0][1]*b[1][2]*b[2][0] + b[0][2]*b[1][0]*b[2][1] - b[0][2]*b[1][1]*b[2][0] - b[0][0]*b[1][2]*b[2][1] - b[0][1]*b[1][0]*b[2][2] );
// make subdet A3,0
row=3; col=0;
ii=0, jj=0;
for( i=0; i<n; i++) {
if (i == row) continue;
for ( j=0; j<n; j++) {
if (j == col) continue;
b[ii][jj] = a[i][j];
jj++;
}
ii++; jj=0;
}
result -= a[3][0] * ( b[0][0]*b[1][1]*b[2][2] + b[0][1]*b[1][2]*b[2][0] + b[0][2]*b[1][0]*b[2][1] - b[0][2]*b[1][1]*b[2][0] - b[0][0]*b[1][2]*b[2][1] - b[0][1]*b[1][0]*b[2][2] );
}
if ( n >=1 && n <= 4 ) {
printf("det(A)=%d\n", result);
} else {
printf("Oh... I can't.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment