写了一段计算行列式的代码,运行慢。大家有什么优化建议。
计算行列式的一段程序。程序主体部分在det.c中。1.c中:unsigned n = 12; n取11以及以下时,运行时间挺短的。n取12时,运行时间是1分钟。n取13时,要12分钟。
det.h
程序代码:
#ifndef DET_H #define DET_H #include <math.h> #include <stdio.h> #include <stdlib.h> double det(double *matrix, unsigned size_n); #endif
det.c
程序代码:
#include "det.h" double det(double *matrix, unsigned size_n) { if (size_n == 1) return *matrix; else { double sum = 0.0; double *slice = malloc(sizeof(double) * pow(size_n - 1, 2)); for (int i = 0; i < size_n; ++i) { int cnt = 0; for (int j = 1; j < size_n; ++j) { for (int k = 0; k < size_n; ++k) { if (i != k) { slice[cnt++] = matrix[j * size_n + k]; } } } sum += pow(-1, i) * det(slice, size_n - 1) * matrix[i]; } free(slice); return sum; } }
1.c
程序代码:
#include "det.h" #include <stdio.h> int main(void) { double a[1] = {1}; printf("%lf\n", det(a, 1)); double b[4] = {1, 2, 3, 4}; printf("%lf\n", det(b, 2)); double c[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; printf("%lf\n", det(c, 3)); unsigned n = 12; double *d = malloc(sizeof(double) * pow(n, 2)); srand(0); for (int i = 0; i < pow(n, 2); ++i) { d[i] = 0.03*(rand() % 51 + 19); } printf("%lf\n", det(d, n)); // getchar(); return 0; }