#include <bits/stdc++.h>
using namespace std;
const long long INF = (long long)1 << 62;
const long long MOD = 1e9 + 7;
const int iINF = 1 << 30;
const double PI = 3.14159265359;
void solve() {
  long long d, m;
  cin >> d >> m;
  long long curr = 1;
  for (; curr * 2 <= d; curr *= 2)
    ;
  long long nxt = d;
  long long s = 0;
  while (nxt >= 1) {
    long long term = (s + 1) % m;
    s = (s + (nxt - curr + 1) * term % m) % m;
    nxt = curr - 1;
    curr /= 2;
  }
  cout << s << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
