#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1);
const int N = 1e6 + 6, mod = 998244353, M = 1e9 + 7;
const long long MAX = 1e15;
int T, m;
long long d;
vector<long long> t;
long long moding(long long x, int m) {
  x %= m;
  while (x < 0) x += m;
  return x;
}
long long slv(long long d, int m) {
  long long ans = 1;
  for (int i = 0; i < t.size(); i++) {
    if (d < t[i]) break;
    ans = moding(ans * (min(d, t[i + 1] - 1) - t[i] + 2), m);
  }
  return moding(ans - 1, m);
}
int main() {
  d = 1;
  while (d < MAX) {
    t.push_back(d);
    d *= 2;
  }
  cin >> T;
  while (T--) {
    cin >> d >> m;
    cout << slv(d, m) << '\n';
  }
  return 0;
}
