#include <bits/stdc++.h>
using namespace std;
long long d, P;
int m = 0;
long long n[35], dp[35][35];
void init() {
  for (long long i = 1, x = 1; x <= d; x *= 2, ++i) {
    if (x * 2 <= d)
      n[i] = (1 << (i - 1));
    else {
      n[i] = d - (1 << (i - 1)) + 1;
      m = i;
      break;
    }
  }
  dp[0][0] = 1;
  for (int i = 1; i <= m; i++) {
    for (int j = 0; j <= i; j++) {
      dp[i][j] = dp[i - 1][j];
      if (j >= 1) dp[i][j] = (dp[i][j] + dp[i - 1][j - 1] * n[i] % P) % P;
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  int T;
  cin >> T;
  while (T--) {
    cin >> d >> P;
    init();
    long long ans = 0;
    for (int j = 1; j <= m; j++) {
      ans = (ans + dp[m][j]) % P;
    }
    cout << ans << endl;
  }
  return 0;
}
