Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- double** allocateMemory(double **matrix, int n);
- double** readFromFile(char* fp, int *n);
- double calculateDeterminant(double **matrix, int n);
- void freeMemory(double **tempMatrix, int n);
- int main(int argc, char **argv) {
- if(argc < 2) {
- printf("Too few arguments");
- exit(1);
- } else if(argc > 2) {
- printf("Too few arguments");
- exit(1);
- }
- int n;
- //int i, j;
- double **matrix = readFromFile(argv[1], &n);
- /*for (i = 0; i < n ; ++i)
- {
- for (j = 0; j < n ; ++j)
- printf("%f ", matrix[i * n + j]);
- printf("\n");
- }*/
- printf("%f \n", calculateDeterminant(matrix, n));
- freeMemory(matrix, n);
- }
- double** allocateMemory(double **matrix, int n) {
- matrix = (double**)malloc(n * sizeof(double));
- for(int i = 0; i < n; ++i) {
- matrix[i] = (double*)malloc(n * sizeof(double));
- if(!matrix[i])
- exit(4);
- }
- return matrix;
- }
- double** readFromFile(char* fp, int *n) {
- FILE *file = fopen(fp, "r");
- if (file == NULL)
- {
- printf("Can't open the file\n");
- exit(1);
- }
- fscanf(file, "%d\n", n);
- double **matrix;
- matrix = allocateMemory(matrix, *n);
- for (int i = 0; i < *n ; ++i) {
- for (int j = 0; j < *n ; ++j)
- {
- if (fscanf(file, "%lf", &matrix[i][j]) < 0) {
- printf("This isn't square matrix or dimension mismatch :(\n");
- exit(1);
- }
- }
- }
- fclose(file);
- return matrix;
- }
- double calculateDeterminant(double **matrix, int n) {
- double determinant = 0;
- if (n < 1) {
- printf("Error 1: this isn't matrix\n");
- exit(1);
- } else if (n == 1) {
- return matrix[0][0];
- } else if (n == 2) {
- return (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]);
- } else if (n > 2) {
- double **temporaryMatrix;
- allocateMemory(temporaryMatrix, n - 1);
- for (int i = 0; i < n; i++) {
- for (int j = 1; j < n; j++) {
- for (int k = 0; k < n; k++) {
- if (k == i) {
- } else if ((i == 0) || (k > i)) {
- temporaryMatrix[j - 1][(k - 1)] = matrix[j][k];
- } else {
- temporaryMatrix[j - 1][k] = matrix[j][k];
- }
- }
- }
- if((i + 1) % 2 == 0){
- determinant = determinant + (-1 * matrix[0][i] * calculateDeterminant(temporaryMatrix, n -1));
- } else {
- determinant = determinant + matrix[0][i] * calculateDeterminant(temporaryMatrix, n -1);
- }
- }
- freeMemory(temporaryMatrix, (n-1));
- }
- return determinant;
- }
- void freeMemory(double **tempMatrix, int n) {
- for (int i = 0; i < n; ++i) {
- free(tempMatrix[i]);
- }
- free(tempMatrix);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement