#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
using ii = pair<int, int>;
using vi = vector<int>;
using vii = vector<ii>;
using vll = vector<ll>;
using graph = vector<vi>;
const int MAXN = 2e5 + 5;
const int MAXM = 2e2 + 5;
ll m, d;
ll dp[50];
ll sol(int i) {
  if ((1 << i) > d) {
    return 0;
  }
  if ((1 << i + 1) > d) {
    return d - (1 << i) + 1;
  }
  if (dp[i] != -1) return dp[i];
  ll ans = (1 << i) % m, aux = 1;
  for (int j = i + 1; j <= 30; ++j) {
    aux = (aux + sol(j)) % m;
  }
  return dp[i] = ans * aux % m;
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    scanf("%lld %lld", &d, &m);
    ll ans = 0;
    memset(dp, -1, sizeof dp);
    for (int i = 0; i <= 30; ++i) {
      ans = (ans + sol(i)) % m;
    }
    printf("%lld\n", ans);
  }
}
