Advertisement
JosepRivaille

P74219: Fibonacci numbers (2)

Mar 24th, 2016
543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. typedef vector<int> Row;
  6. typedef vector<Row> Matrix;
  7.  
  8.  
  9. Matrix mult_M(const Matrix &M, const Matrix &N, int m)
  10. //Strassen algorithm
  11. {
  12.   int p1, p2, p3, p4, p5, p6, p7;
  13.   p1 = M[0][0]*(N[0][1]-N[1][1]); // A(F-H)
  14.   p2 = (M[0][0]+M[0][1])*N[1][1]; // (A+B)H
  15.   p3 = (M[1][0]+M[1][1])*N[0][0]; // (C+D)E
  16.   p4 = M[1][1]*(N[1][0]-N[0][0]); // D(G-E)
  17.   p5 = (M[0][0]+M[1][1])*(N[0][0]+N[1][1]); // (A+D)(E+H)
  18.   p6 = (M[0][1]-M[1][1])*(N[1][0]+N[1][1]); // (B-D)(G+H)
  19.   p7 = (M[0][0]-M[1][0])*(N[0][0]+N[0][1]); // (A-C)(E+F)
  20.   Matrix R(2, Row(2));
  21.   R[0][0] = (p5 + p4 - p2 + p6)%m;
  22.   R[0][1] = (p1 + p2)%m;
  23.   R[1][0] = (p3 + p4)%m;
  24.   R[1][1] = (p1 + p5 - p3 - p7)%m;
  25.   return R;
  26. }
  27.  
  28. Matrix fibonacci(const Matrix &M, const int &n, const int &m)
  29. // (0 1)^n-1   (1)   (Fn  )
  30. // (   )     * ( ) = (    )
  31. // (1 1)       (1)   (Fn-1)
  32. {
  33.     if (n <= 1)
  34.         return M;
  35.     else {
  36.         Matrix R = fibonacci(M, n/2, m);
  37.         Matrix aux = mult_M(R, R, m);
  38.         if (n%2 == 0) return aux;
  39.         else return mult_M(aux, M, m);
  40.     }
  41. }
  42.  
  43.  
  44. int main()
  45. {
  46.     Matrix M(2, Row(2, 1));
  47.     M[0][0] = 0;
  48.     //Basic Fibonacci Matrix
  49.     int n, m;
  50.     while (cin >> n >> m) {
  51.         if (n <= 1) cout << n << endl;
  52.         else {
  53.             Matrix aux = fibonacci(M, n-1, m); // M^n-1
  54.             cout << (aux[0][0] + aux[0][1])%m << endl;
  55.         }
  56.     }
  57. }
  58.  
  59. //JosepRivaille
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement