#include #define po2(x) (II(1) << (x)) using namespace std; typedef long long LL; typedef __int128 II; LL Magic; const int W = 64; int d,p; LL N; void getMagic() { II x = po2(W-1) - po2(W-1)%d - 1, t; for(p=0;t=po2(p),t<=x*(d-t%d);p++); if (p < W) p = W, t = po2(W); Magic = (t + d - t % d) / d; } LL MOD(LL x) { LL t = II(x) * Magic >> W; if (Magic < 0) t += x; return x - (t >> (p - W)) * d; } LL f(LL x) { return MOD(x * (x + 4)); } int main() { scanf("%lld",&N); N++; scanf("%d",&d);getMagic(); LL p1 = 2 % d, p2 = 12 % d; LL now = 1; if (N == 1) return printf("%lld\n",2LL%d),0; while(p1 != p2) { now++; p1 = f(p1); p2 = f(p2); p2 = f(p2); if (now == N) { printf("%lld\n",p1); return 0; } } N -= now; LL p = p1; now = 0; while(true) { now++; p1 = f(p1); p2 = f(p2); p2 = f(p2); if (now == N) { printf("%lld\n",p1); return 0; } if (p1 == p2) break; } N %= now; for (LL i=1;i<=N;i++) p = f(p); printf("%lld\n",p); }