#include <bits/stdc++.h>
using namespace std;
template <typename T>
void print(T vec) {
  for (auto d : vec) cout << d << ' ';
  cout << '\n';
}
template <typename T>
void print2D(T mat) {
  for (auto vec : mat) print(vec);
}
int d, m;
void solve() {
  cin >> d >> m;
  int64_t ans = 1;
  for (int i = 0; i < 30; i++) {
    if (d < (1 << i)) break;
    ans = ans * (std::min((1 << (i + 1)) - 1, d) - (1 << i) + 2) % m;
  }
  ans--;
  if (ans < 0) ans += m;
  cout << ans << '\n';
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
}
