void powMatrix(int **C, int **A, int k, int ***powers, char *computed, int N) { int **T, i; T = (int **) malloc(MAX_N * sizeof(int *)); for ( i=0; i<MAX_N; ++i ) T[i] = (int *) malloc(MAX_N * sizeof(int)); if ( (int)computed[k] ) cpyMatrix(C, A, N); else { if ( k==1 ) cpyMatrix(powers[k], A, N); else if ( k%2==0 ) { powMatrix(T, A, k/2, powers, computed, N); mulMatrix(powers[k], T, T, N); } else { powMatrix(T, A, k-1, powers, computed, N); mulMatrix(powers[k], A, T, N); } computed[k] = 1; cpyMatrix(C, powers[k], N); } for ( i=0; i<MAX_N; ++i ) free(T[i]); free(T); }
int main(int argc, char const *argv[]) { printf("\nEnter matrix filename, or type 'enter' to enter.\n"); char promptString[100]; scanf("%s", promptString); if (strcmp(promptString, "enter") == 0) { printf("Enter the number of rows: "); scanf("%d", &rows); printf("Enter the number of columns: "); scanf("%d", &columns); printf("\nNote: you can enter '|' to place the augmentation bar.\n"); for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { double input; printf("Row %d Column %d: ", i+1, j+1); scanf("%lf", &(input)); matrix[i][j] = input; } } } else { mtrxFromFile(promptString); } // Backup cpyMatrix(matrix, prevMatrix); printf("\n"); // Main loop while (true) { // Print matrix printMatrix(); // Get command printf("\nCommand: ('a'dd, 'm'ul, 's'wap, 'u'ndo, 'r'un solver): "); char command[5]; scanf("%s", command); if (command[0] == 'a') { // Backup cpyMatrix(matrix, prevMatrix); int row; printf(" target row: "); scanf("%d", &row); int srcRow; printf(" source row: "); scanf("%d", &srcRow); double factor; printf(" factor: "); scanf("%lf", &factor); mtrxAdd(matrix, row, srcRow, factor); } else if (command[0] == 'm') { // Backup cpyMatrix(matrix, prevMatrix); int row; printf(" row: "); scanf("%d", &row); double factor; printf(" factor: "); scanf("%lf", &factor); mtrxMult(matrix, row, factor); } else if (command[0] == 's') { // Backup cpyMatrix(matrix, prevMatrix); int row1; printf(" target row: "); scanf("%d", &row1); int row2; printf(" source row: "); scanf("%d", &row2); mtrxSwap(matrix, row1, row2); } else if (command[0] == 'u') { printf("\n\nUNDO. You may only undo once at a time.\n"); cpyMatrix(prevMatrix, matrix); } else if (command[0] == 'r') { // Backup cpyMatrix(matrix, prevMatrix); // Rest all pivots pivotRow = 0; pivotColumn = 0; while (pickAndSwapPivot()) { if (matrix[pivotRow - 1][pivotColumn - 1] != 1) { // Scale double factor = 1.0 / matrix[pivotRow - 1][pivotColumn - 1]; mtrxMult(matrix, pivotRow, factor); } // Clear column for (int i = 0; i < rows; ++i) { if (i == pivotRow - 1) continue; double value = matrix[i][pivotColumn - 1]; if (fabs(value) >= ZERO_THRESH) { // Subtract multiples mtrxAdd(matrix, i + 1, pivotRow, -value); } } printMatrix(); } printf("\nSolved matrix.\n"); } else { printf("\n\nRETRY. Use only one letter.\n"); } printf("\n"); } return 0; }