#include <bits/stdc++.h>
using namespace std;
long long MOD = 1e9 + 7;
const long long INF = 1e18;
const double EPS = 1e-6;
const int MAX_LOG = 30;
namespace modOp {
long long add(long long a, long long b, long long mod = MOD) {
  return (a + b) % mod;
}
void ADD(long long& a, long long b, long long mod = MOD) { a = (a + b) % mod; }
long long sub(long long a, long long b, long long mod = MOD) {
  return (a - b + mod) % mod;
}
void SUB(long long& a, long long b, long long mod = MOD) {
  a = (a - b + mod) % mod;
}
long long mul(long long a, long long b, long long mod = MOD) {
  return (long long)a * b % mod;
}
void MUL(long long& a, long long b, long long mod = MOD) {
  a = (long long)a * b % mod;
}
}  // namespace modOp
using namespace modOp;
long long dp[MAX_LOG + 1];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    long long d, m;
    cin >> d >> m;
    MOD = m;
    memset(dp, 0, sizeof dp);
    dp[0] = 1ll;
    long long sum = 2ll;
    for (long long i = 1; i <= MAX_LOG; ++i) {
      if ((1ll << i) > d) break;
      long long cnt = min((1ll << i), d - (1ll << i) + 1ll);
      ADD(dp[i], cnt * sum);
      ADD(sum, dp[i]);
    }
    SUB(sum, 1);
    cout << sum << '\n';
  }
  return 0;
}
