#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e18;
const int32_t mod = 1000000007;
const long long N = 3e5 + 5;
long long solve() {
  long long d, m;
  cin >> d >> m;
  long long bit = 0;
  for (long long i = 31; i >= 0; i--) {
    if (d & (1 << i)) {
      bit = i;
      break;
    }
  }
  vector<long long> vals;
  for (long long i = 0; i < bit; i++) {
    vals.push_back(1 << i);
  }
  vals.push_back(d - (1 << bit) + 1);
  long long n = (long long)(vals.size());
  long long dp[n + 1][n + 1];
  memset(dp, 0, sizeof dp);
  for (long long i = 0; i < n; i++) {
    dp[1][i] = vals[i];
    if (i > 0) dp[1][i] += dp[1][i - 1];
  }
  for (long long i = 2; i < n + 1; i++) {
    for (long long j = i - 1; j < n; j++) {
      dp[i][j] = vals[j] * dp[i - 1][j - 1];
      dp[i][j] %= m;
      dp[i][j] += dp[i][j - 1];
    }
  }
  long long ans = 0;
  for (long long i = 1; i < n + 1; i++) {
    ans += dp[i][n - 1];
    ans %= m;
  }
  cout << ans << '\n';
  return 0;
}
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cout << fixed << setprecision(20);
  long long tests = 1;
  cin >> tests;
  for (long long i = 1; i <= tests; i++) {
    solve();
  }
  return 0;
}
