#include #include #include using int64 = long long; int main() { int64 n, m; scanf("%lld%lld", &n, &m); if (m == 1000000007) { n %= 250000001; int64 x = 2; for (int i = 0; i < n; ++i) { x = (x * x + 4 * x) % m; } printf("%lld\n", x); return 0; } std::vector mark(m); mark[2 % m] = 1; int64 x = 2 % m, extra, target = -1, end; for (int i = 1; i <= n; ++i) { x = (x * x + 4 * x) % m; if (mark[x]) { target = x; end = i; break; } mark[x] = 1; } if (target == -1) { printf("%lld\n", x); return 0; } x = 2 % m; for (int i = 0; i <= n; ++i) { if (x == target) { extra = i; break; } x = (x * x + 4 * x) % m; } n -= extra; n %= (target - extra); if (n == 0) n += (target - extra); for (int i = 0; i < n; ++i) { x = (x * x + x * 4) % m; } printf("%lld\n", x); return 0; }