#include <bits/stdc++.h>
using namespace std;
int t;
long long d, m;
vector<long long> v;
int main() {
  cin >> t;
  while (t--) {
    cin >> d >> m;
    long long t1 = 1;
    v.clear();
    while (1) {
      if (d <= (t1 << 1) - 1) {
        v.push_back(d - t1 + 1);
        break;
      }
      v.push_back(t1);
      t1 = t1 << 1;
    }
    long long ans = v[0], tmp = v[0];
    for (int i = 1; i < v.size(); i++) {
      tmp = ans * v[i] + v[i];
      tmp %= m;
      ans += tmp;
      ans %= m;
    }
    ans %= m;
    cout << ans << endl;
  }
  return 0;
}
