#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    long long d, m;
    cin >> d >> m;
    vector<long long> cnt(31, 0);
    cnt[1] = 1;
    long long cur = 2, pre = 1;
    for (int i = 2; i < 31; i++) {
      cur *= 2;
      cnt[i] = min(d, cur) - pre;
      if (min(d, cur) == cur) cnt[i]--;
      pre += cnt[i];
      if (d < cur) break;
    }
    vector<vector<long long> > dp(31, vector<long long>(31, 0));
    for (int i = 1; i < 31; i++) {
      dp[i][1] = dp[i - 1][1] + cnt[i];
    }
    for (int i = 2; i < 31; i++) {
      for (int j = 2; j < i + 1; j++) {
        dp[i][j] = dp[i - 1][j - 1] * cnt[i];
        dp[i][j] %= m;
        dp[i][j] += dp[i - 1][j];
        dp[i][j] %= m;
      }
    }
    long long ans = 0;
    for (int j = 1; j < 31; j++) ans = (ans + dp[30][j]) % m;
    cout << ans << endl;
  }
  return 0;
}
