#include using namespace std; using ll = long long; int main(){ ios::sync_with_stdio(false); cin.tie(0); int T; cin >> T; while(T--){ string s; ll n = 0, m; cin >> s >> m; for(int i = 0; i < s.size(); i++){ n *= 10; n += s[i] - '0'; n %= m; } cout << (n * (n + 1) / 2) % m << '\n'; } }