#define _USE_MATH_DEFINES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; int T; //ループの回数は適宜修正 ll power(ll a, ll b, ll m) { ll p = a, ans = 1; for(int i = 0; i < 60; i++) { ll wari = (1LL << i); if((b / wari) % 2 == 1) { ans = (ans * p) % m; } p = (p * p) % m; } return ans; } int main() { cin >> T; vector ansv; while(T--) { string N; ll M; ll ans = 0; cin >> N >> M; ll now = 0; for(int i = 0; i < (int)N.size(); ++i) { ll n = ll(N[i]-'0'); now = now*10+n; now %= M; } ans = now*(now+1)/2; ans %= M; ansv.push_back(ans); } for(int ans : ansv) cout << ans << endl; }