Advertisement
HeroBaga

Untitled

Oct 4th, 2021
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4. #define N 5
  5.  
  6. void getCfactor(int M[N][N], int t[N][N], int p, int q, int n) {
  7. int i = 0, j = 0;
  8. for (int r = 0; r < n; r++) {
  9. for (int c = 0; c < n; c++) //Copy only those elements which are not in given row r and column c: {
  10. if (r != p && c != q) {
  11. t[i][j++] = M[r][c]; //If row is filled increase r index and reset c index
  12. if (j == n - 1) {
  13. j = 0;
  14. i++;
  15. }
  16. }
  17. }
  18. }
  19.  
  20.  
  21. int DET(int M[N][N], int n) {
  22. int D = 0;
  23. if (n == 1)
  24. return M[0][0];
  25. int t[N][N]; //store cofactors
  26. int s = 1; //store sign multiplier
  27. //To Iterateeach elementof firstrow
  28. for (int f = 0; f < n; f++) {
  29. //For Getting Cofactor of M[0][f] do
  30. getCfactor(M, t, 0, f, n);
  31. D += s * M[0][f] * DET(t, n - 1);
  32. s = -s;
  33. }
  34. return D;
  35. }
  36.  
  37. void ADJ(int M[N][N], int adj[N][N]) {
  38. if (N == 1) {
  39. adj[0][0] = 1;
  40. return;
  41. }
  42. int s = 1, t[N][N];
  43. for (int i = 0; i < N; i++) {
  44. for (int j = 0; j < N; j++) {
  45. //To get cofactor of M[i][j]
  46. getCfactor(M, t, i, j, N);
  47. s = ((i + j) % 2 == 0) ? 1 : -1; //sign of adj[j][i] positive if sum of row and column indexes is even.
  48. adj[j][i] = (s) * (
  49. DET(t, N - 1)); //Interchange rows and columns to get the transpose of the cofactor matrix
  50. }
  51. }
  52. }
  53.  
  54. bool INV(int M[N][N], float inv[N][N]) {
  55. int det = DET(M, N);
  56. if (det == 0) {
  57. cout << "can't find its inverse";
  58. return false;
  59. }
  60. int adj[N][N];
  61. ADJ(M, adj);
  62. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) inv[i][j] = adj[i][j] / float(det);
  63. return true;
  64. }
  65.  
  66. template<class T>
  67. void print(T A[N][N]) {
  68. for (int i = 0; i < N; i++) {
  69. for (int j = 0; j < N; j++)
  70. cout << A[i][j] << " ";
  71. cout << endl;
  72. }
  73. }
  74.  
  75. int main() {
  76. int M[N][N] = {
  77. {1, 2, 3, 4, -2},
  78. {-5, 6, 7, 8, 4},
  79. {9, 10, -11, 12, 1},
  80. {13, -14, -15, 0, 9},
  81. {20, -26, 16, -17, 25}
  82. };
  83. float inv[N][N];
  84. cout << "Input matrix is :\n";
  85. print(M);
  86. cout << "\nThe Inverse is :\n";
  87. if (INV(M, inv)) print(inv);
  88. return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement