#include <bits/stdc++.h>   using namespace std;   int hx[] = {-2, -2, -1, -1, 1, 1, 2, 2};   int hy[] = {-1, 1, -2, 2, -2, 2, -1, 1};   int dx[] = {1, -1, 0, 0};   int dy[] = {0, 0, 1, -1};   int nx[] = {1, -1, 0, 0, -1, 1, 1, -1};   int ny[] = {0, 0, 1, -1, 1, -1, 1, -1};   class pt {    public:     int x, y;   };   int main() {     int t = 1;     while (t--) {       long long n, m;       cin >> n >> m;       long long ans = 1, tmp = 3;       for (int i = 0; i < 32; i++) {         if (n & 1 << i) ans = (ans * tmp) % m;         tmp = (tmp * tmp) % m;       }       if (ans == 0) ans = m;       cout << ans - 1 << endl;     }     return 0;   }   