Determinant Using Upper Triangular Form!!!
Given a matrix, our objective is to compute the determinant of the matrix. The determinant is to be computed by reducing the matrix to its upper triangular form.
The following steps are used to obtain the upper triangular form of a matrix:
- Call the element in the first row and first column of the matrix the pivot element. If the pivot is zero, then we need to do a row transform as described below:
- Find a row below the current row for which the element in the first column is not zero.
- Interchange this entire row with the first row. After a row transform, the element in the first row and first column should be non-zero, and we have a non-zero pivot.
- If you cannot find a row which makes the pivot non-zero, then the value of the determinant is zero, and further steps are not to be carried out.
- For each row except the first row, compute the new value of each element as follows:
New value of element at ith row, jth column = old value of element - (value of element at 1st row, jth column * (old value of element at ith row, 1st column / value of pivot)).
For example,
new value of element at (1,2) = old value of element at (1,2) - (value of element at (0,2) * (old value of element at (1,0) / value of element at (0,0))).
Consider the following matrix:
+- -+
| 2 4 6 |
| 1 3 5 |
| 3 7 8 |
+- -+
We want to find the new value for element at (1,2). Then as calculated above,
new value for element at (1,2) = 5 - (6 * (1 / 2)).
The effect of this operation is to make the value of the element in the first column of each row 0, except the first row. Notice that the very first row remains unchanged after this operation.
- Now recursively carry out operations 1 & 2 for the submatrix obtained after removing the first row and first column. For example given the above matrix, you would now carry out steps 1 & 2 for the submatrix
+- -+
| 3 5 |
| 7 8 |
+- -+
Continue until all elements below the diagonal in the matrix are 0.
After these steps, we should have a matrix in the following form:
+- -+
| a b c d |
| 0 e f g |
| 0 0 h i |
| 0 0 0 j |
+- -+
i.e., all the elements below the diagonal are zero.
The determinant of a matrix is then simply the product of the diagonal elements, multiplied with (-1)^(number of row transforms).
Thus, if we want the determinant of the above matrix, we just multiply the diagonal elements (a * e * h * j) with (-1) ^ (# of row transforms required). For example, if we carry out the row transforms twice, the determinant would be (a * e * h * j) * (-1) ^ 2.
Now that you know how to compute the determinant, you are expected to do the following:
Input the size of the matrix (say n)
Input the n x n matrix elements
Output the value of the determinant
Note that you should not display any extraneous prompts, output etc.
Sample:
Input:
3
1 6
9 13
Output:
-41
Input:
4
3 4 8 9
6 8 16 9
1 8 -1 12
-1 4 2 8
Output:
-1368
Input:
4
1 3 -5 1
-1 5 2 1
0 0 0 1
0 8 -3 3
Output:
0