Advertisement
Schnuk

Untitled

Feb 22nd, 2021
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int LinearMethod(int n)
  5. {
  6. int a = 1;
  7. int b = 1;
  8. int c = 2;
  9. if (n == 3)
  10. return c;
  11. if (n <= 2)
  12. return b;
  13. for (int i = 3; i < n; i++)
  14. {
  15. a = b;
  16. b = c;
  17. c = a + b;
  18. }
  19. return c;
  20. }
  21.  
  22. int RecursiveMethod(int n)
  23. {
  24. if (n <= 2)
  25. return 1;
  26. return RecursiveMethod(n - 1) + RecursiveMethod(n - 2);
  27. }
  28.  
  29. int** MatrixMultiplication(int** matrix2, int** matrix1)
  30. {
  31. int e1 = matrix1[0][0] * matrix2[0][0] + matrix1[0][1] * matrix2[1][0];
  32. int e2 = matrix1[0][0] * matrix2[0][1] + matrix1[0][1] * matrix2[1][1];
  33. int e3 = matrix1[1][0] * matrix2[0][0] + matrix1[1][1] * matrix2[1][0];
  34. int e4 = matrix1[1][0] * matrix2[0][1] + matrix1[1][1] * matrix2[1][1];
  35. return new int* [2]{ new int[2]{ e1, e2 }, new int[2]{ e3, e4 } };
  36. }
  37.  
  38. int** BinaryExponentiation(int** matrix, int n)
  39. {
  40. if (n == 0)
  41. return new int* [2]{ new int[2]{ 1, 0 }, new int[2]{ 0, 1 } };
  42. if (n % 2 == 1)
  43. return MatrixMultiplication(BinaryExponentiation(matrix, n - 1), matrix);
  44. else
  45. {
  46. int** matrixTemp = BinaryExponentiation(matrix, n / 2);
  47. return MatrixMultiplication(matrixTemp, matrixTemp);
  48. }
  49. }
  50.  
  51. int MatrixMethod(int n)
  52. {
  53. int** matrix = new int* [2]{ new int[2]{ 1, 1 }, new int[2]{ 1, 0 } };
  54. return BinaryExponentiation(matrix, n)[0][1];
  55. }
  56.  
  57. int main()
  58. {
  59. cout << LinearMethod(9) << endl;
  60. cout << RecursiveMethod(9) << endl;
  61. cout << MatrixMethod(9);
  62. }
  63.  
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement