#include <bits/stdc++.h>
using namespace std;
long long count(long long n, long long v) {
  assert(v >= n);
  long long rhs = 2 * n;
  return min(v + 1, rhs) - n;
}
void rsolve() {
  long long d, m;
  cin >> d >> m;
  long long ret = 0;
  long long v = 1;
  while (v <= d) {
    long long amt = count(v, d);
    long long inc = ret + 1;
    ret += inc * amt;
    ret %= m;
    v *= 2;
  }
  cout << ret << "\n";
}
void solve() {
  int t;
  cin >> t;
  while (t--) rsolve();
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  solve();
}
