#include <bits/stdc++.h>
using namespace std;
const int MOD = (int)1e9 + 7;
const int INF = (int)1e9;
const long long LINF = (long long)1e18;
const long double PI = acos((long double)-1);
const long double EPS = 1e-9;
long long gcd(long long a, long long b) {
  if (a < b) swap(a, b);
  long long r;
  while (b) {
    r = a % b;
    a = b;
    b = r;
  }
  return a;
}
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
long long fpow(long long n, long long k, long long p = MOD) {
  long long r = 1;
  for (; k; k >>= 1) {
    if (k & 1) r = r * n % p;
    n = n * n % p;
  }
  return r;
}
template <class T>
void setmin(T& a, T val) {
  if (a > val) a = val;
}
template <class T>
void setmax(T& a, T val) {
  if (a < val) a = val;
}
void addmod(int& a, int val, int p = MOD) {
  if ((a = (a + val)) >= p) a -= p;
}
void submod(int& a, int val, int p = MOD) {
  if ((a = (a - val)) < 0) a += p;
}
int mult(int a, int b, int p = MOD) { return (long long)a * b % p; }
int inv(int a, int p = MOD) { return fpow(a, p - 2, p); }
long long d, m;
vector<long long> dp(33);
long long f(long long bits) {
  if (dp[bits] != -1ll) return dp[bits];
  long long sum = 0;
  for (int i = (0); i < (bits); i++) {
    sum += f(i);
    sum %= m;
  }
  dp[bits] = (fpow(2, bits - 1, m) * sum) % m;
  return dp[bits];
}
void init() {
  for (int i = (0); i < (33); i++) dp[i] = -1;
  dp[0] = 1;
  dp[1] = 1;
}
void solve() {
  cin >> d >> m;
  long long t = d, bits = 0;
  while (t) {
    t /= 2;
    bits++;
  }
  init();
  f(bits);
  long long ans = 0ll;
  for (int i = (0); i < (bits); i++) {
    ans += dp[i];
    ans %= m;
  }
  long long multiplier = (d - fpow(2, bits - 1, m) + 1 + m) % m;
  ans += (ans * multiplier) % m;
  ans += m - 1;
  ans %= m;
  cout << ans << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
