#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 10;
int d, mod;
int dp[33];
int pw[33];
void ok(int &x) {
  if (x >= mod) x -= mod;
}
void fill_dp() {
  pw[0] = 1;
  for (int i = 1; i < 33; i++) {
    pw[i] = pw[i - 1] + pw[i - 1];
    ok(pw[i]);
  }
  dp[0] = 1;
  for (int i = 1; i < 33; i++) {
    dp[i] = dp[i - 1] + 1ll * dp[i - 1] * pw[i - 1] % mod;
    ok(dp[i]);
  }
}
int main() {
  ios_base ::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  int T;
  cin >> T;
  while (T--) {
    cin >> d >> mod;
    fill_dp();
    int ans = 0;
    for (int i = 30; ~i; i--) {
      if (d & (1 << i)) {
        int t = d - (1 << i) + 1;
        ans += 1ll * t * dp[i] % mod;
        ok(ans);
        ans += dp[i];
        ok(ans);
        ans += mod - 1;
        ok(ans);
        break;
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
