Created
December 30, 2022 15:15
-
-
Save srezasm/eb0272975bc7eb63e1c7671a2bcc661c to your computer and use it in GitHub Desktop.
Determinant algorithm in c++
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 <math.h> | |
#include <stdio.h> | |
#include <iostream> | |
int Determinant(int**, int); | |
void PrintMatrix(int**, int, int); | |
int** ReadMatrix(int, int); | |
int main(int argc, char const* argv[]) { | |
int n; | |
printf("enter dimentions: "); | |
scanf("%d", &n); | |
printf("enter your matrice:\n"); | |
int** mat = ReadMatrix(n, n); | |
printf("determinant is: %d\n", Determinant(mat, n)); | |
return 0; | |
} | |
int** ReadMatrix(int r, int c) { | |
int** mat = 0; | |
mat = new int*[r]; | |
for (int i = 0; i < r; i++) { | |
mat[i] = new int[c]; | |
for (int j = 0; j < c; j++) { | |
scanf("%d", &mat[i][j]); | |
} | |
} | |
return mat; | |
} | |
void PrintMatrix(int** mat, int r, int c) { | |
for (int i = 0; i < r; i++) { | |
for (int j = 0; j < c; j++) { | |
printf("%d ", mat[i][j]); | |
} | |
printf("\n"); | |
} | |
} | |
int Determinant(int** mat, int n) { | |
int det = 0; | |
if (n == 2) | |
return (mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]); | |
else { | |
int** submat = new int*[n]; | |
for (int i = 0; i < n; i++) | |
submat[i] = new int[n]; | |
int r = 0, c = 0; | |
for (int i = 0; i < n; i++) { | |
for (int j = 1; j < n; j++) { | |
for (int k = 0; k < n; k++) { | |
if (k == i) | |
continue; | |
submat[r][c] = mat[j][k]; | |
c++; | |
} | |
c = 0; | |
r++; | |
} | |
r = 0; | |
printf("\n"); | |
PrintMatrix(submat, n - 1, n - 1); | |
printf("\n"); | |
det += pow(-1, i) * mat[0][i] * Determinant(submat, n - 1); | |
} | |
} | |
return det; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment