#include using namespace std; typedef long long ll; typedef pair P; #define REP(i,n) for(ll i=0;i> T; while(T--){ string N; cin >> N >> M; M*=2; ll x=f(N); cout << (x*(x+1)%M)/2 << '\n'; } return 0; }