aboutsummaryrefslogtreecommitdiff
path: root/Semestr 4/aisd/themis/FIB.cpp
blob: dd38c5c2c44260860f2b73389fbd0a49f74a970b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

class matrix
{
public:
  ll a, b, c, d;
  static ll m;

  matrix(ll _a = 0, ll _b = 0, ll _c = 0, ll _d = 0) : a(_a), b(_b), c(_c), d(_d) {}

  matrix operator*(const matrix &M) const
  {
    matrix res;
    res.a = (a * M.a + b * M.c) % m;
    res.b = (a * M.b + b * M.d) % m;
    res.c = (c * M.a + d * M.c) % m;
    res.d = (c * M.b + d * M.d) % m;
    return res;
  }
};

ll matrix::m = 1;

matrix fast_pow(matrix M, int w)
{
  matrix res(1, 0, 0, 1);
  while (w)
  {
    if (w % 2 == 1)
      res = res * M;
    M = M * M;
    w >>= 1;
  }
  return res;
}

void solve()
{
  int n, m;
  cin >> n >> m;
  matrix M(0, 1, 1, 1);
  matrix::m = m;
  cout << fast_pow(M, n + 1).a << "\n";
}

int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie();
  int t;
  cin >> t;
  while (t--)
  {
    solve();
  }
}