fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. void det_calc(double *matrix, int pivot[], int dim){
  6. int m, n, p;
  7. double *mat, *row, *col, max;
  8. mat = matrix;
  9. for (p = 0; p < dim; mat += dim, p++){ // Get the pivot
  10. pivot[p] = p;
  11. max = fabs(*(mat + p));
  12. row = mat + dim;
  13. for (n = p + 1; n < dim; n++, row += dim){
  14. if (max < fabs(*(row + p))){
  15. max = fabs(*(row + p));
  16. pivot[p] = n;
  17. col = row;
  18. }
  19. }
  20. if (pivot[p] != p) // If pivot is diff from current row, swap
  21. for (n = 0; n < dim; n++){
  22. max = *(mat + n);
  23. *(mat + n) = *(col + n);
  24. *(col + n) = max;
  25. }
  26. if (*(mat + p) == 0) return; // Singular matrix
  27. row = mat + dim;
  28. for (m = p + 1; m < dim; row += dim, m++) // Get lower triangular matrix
  29. *(row + p) /= *(mat + p);
  30. row = mat + dim;
  31. for (m = p + 1; m < dim; row += dim, m++) // Update matrix
  32. for (n = p + 1; n < dim; n++)
  33. *(row + n) -= *(row + p) * *(mat + n);
  34. }
  35. }
  36.  
  37. int main(void){
  38. int dim;
  39. double result = 1.0;
  40. char line[100];
  41. char *p = line, *beginning = p, *end;
  42. fgets(line, sizeof(line), stdin); // Get the first number
  43. sscanf(line, "%d", &dim); // Convert to int
  44. double matrix[dim][dim];
  45. int pivot[dim]; // Array to track pivot
  46. for (int i = 0; i < dim; i++){
  47. fgets(line, sizeof(line), stdin); // Get next line
  48. while (*p){ // Read until end of line
  49. for (int j = 0; j < dim; j++)
  50. matrix[i][j] = strtod(p, &end); // Convert to double
  51. p++;
  52. }
  53. p = beginning;
  54. }
  55. det_calc(&matrix[0][0], pivot, dim);
  56. for(int i = 0; i < dim; i++) result *= matrix[i][i];
  57. printf("%f", result);
  58. return 0;
  59. }
Success #stdin #stdout 0s 5512KB
stdin
9
0 0 0 0 0 0 2 3 1
0 0 0 7 3 2 3 3 1
0 0 0 0 9 10 2 8 3
0 0 0 0 0 0 0 6 4
0 4 7 10 5 10 5 9 6
0 0 0 0 0 3 9 9 6
2 1 2 1 7 6 3 10 9
0 0 5 7 7 3 10 2 5
0 0 0 0 0 0 0 0 5
stdout
0.000000