#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; while(T--) { string N; ll M; ll ans = 0; cin >> N >> M; reverse(N.begin(), N.end()); for(int i = 0; i < N.size(); ++i) { int n = int(N[i]-'0'); ans += n*power(10,i,M); ans %= M; } ans = ans*(ans+1)/2; ans %= M; cout << ans << endl; } }