#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 %= m; idx++; } ans += m; ans *= (ans+1LL); ans /= 2LL; printf("%lld\n", ans%m); t--; } return 0; }