#include using namespace std; using ll = long long; string N; ll M; void solve(){ cin >> N >> M; reverse(N.begin(), N.end()); ll p10 = 1; ll n = 0; for(char c : N){ n = (n + (c - '0') * p10) % (2 * M); p10 = p10 * 10 % (2 * M); } ll ans = n * (n + 1) / 2 % M; cout << ans << endl; } int main(void){ ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t--)solve(); return 0; }