#include <bits/stdc++.h>
using namespace std;
inline void Boost() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
}
const int NMAX = 66;
int dp[2][NMAX];
int main() {
  Boost();
  int T;
  cin >> T;
  while (T--) {
    long long n, mod, p = 1;
    cin >> n >> mod;
    vector<long long> v;
    for (; p < n; p *= 2) {
      if (p * 2 > n)
        v.push_back(n - p + 1);
      else
        v.push_back(p);
    }
    if (p == n) v.push_back(1);
    int l = v.size() - 1;
    dp[1][l] = v[l];
    dp[0][l] = 1;
    for (int i = l - 1; i >= 0; i--) {
      dp[1][i] = (v[i] * ((dp[0][i + 1] + dp[1][i + 1]) % mod)) % mod;
      dp[0][i] = (dp[0][i + 1] + dp[1][i + 1]) % mod;
    }
    cout << ((dp[0][0] + dp[1][0]) % mod - 1 + mod) % mod << "\n";
  }
  return 0;
}
