fork download
  1. #include <iostream>
  2. #include <complex>
  3.  
  4. void print(const std::complex<double> (&matrix)[2][2])
  5. {
  6. for(const auto& row: matrix) {
  7. for(const auto& c: row)
  8. std::cout << c << ' ';
  9. std::cout << '\n';
  10. }
  11. }
  12.  
  13. void multiply(std::complex<double> (&lhs)[2][2], const std::complex<double> (&rhs)[2][2])
  14. {
  15. std::complex<double> result[2][2];
  16. for(int i = 0; i < 2; ++i) for(int j = 0; j < 2; ++j)
  17. result[i][j] = lhs[i][0]*rhs[0][j] + lhs[i][1]*rhs[1][j];
  18. for(int i = 0; i < 2; ++i) for(int j = 0; j < 2; ++j)
  19. lhs[i][j] = result[i][j];
  20. }
  21.  
  22. void power(std::complex<double> (&matrix)[2][2], unsigned n)
  23. {
  24. std::complex<double> result[2][2] = {{1, 0}, {0, 1}};
  25. for(int i = 0; i < n; ++i)
  26. multiply(result, matrix);
  27. for(int i = 0; i < 2; ++i) for(int j = 0; j < 2; ++j)
  28. matrix[i][j] = result[i][j];
  29. }
  30.  
  31. int main()
  32. {
  33. using namespace std::complex_literals;
  34. std::complex<double> matrix[2][2] =
  35. {{ 1.0 + 0i, 0.0 + 1i},
  36. {-1.0 + 0i, 0.0 - 1i}};
  37. print(matrix);
  38. std::cout << '\n';
  39. power(matrix, 1);
  40. print(matrix);
  41. std::cout << '\n';
  42. power(matrix, 2);
  43. print(matrix);
  44. std::cout << '\n';
  45. }
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
(1,0) (0,1) 
(-1,0) (0,-1) 

(1,0) (0,1) 
(-1,0) (0,-1) 

(1,-1) (1,1) 
(-1,1) (-1,-1)