#include int main () { int t = 0; char n[4000001] = ""; long long m = 0LL; int res = 0; res = scanf("%d", &t); while (t > 0) { long long ans = 0LL; int idx = 0; res = scanf("%s", n); res = scanf("%lld", &m); while (n[idx] != '\0') { ans *= 10LL; ans += (long long)(n[idx]-'0'); ans %= 2LL*m; idx++; } ans *= (ans+1LL); ans /= 2LL; printf("%lld\n", ans%m); t--; } return 0; }