#include <bits/stdc++.h>
using namespace std;
const long long K = 30;
void solve() {
  long long d, m;
  cin >> d >> m;
  vector<long long> dp(K);
  dp[0] = 1;
  for (long long i = 1; i < K; i++) {
    long long can = min((1LL << i), d - (1LL << i) + 1);
    dp[i] = dp[i - 1];
    if (can > 0) {
      dp[i] += (dp[i - 1] * can);
      dp[i] %= m;
    }
    if ((1LL << i) <= d) {
      dp[i] += can;
      dp[i] %= m;
    }
  }
  cout << dp[K - 1] % m << endl;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long q;
  cin >> q;
  while (q--) {
    solve();
  }
}
