#include <bits/stdc++.h>
using namespace std;
long long p;
long long qpow(long long a, long long n) {
  long long res = 1;
  while (n) {
    if (n & 1) res = res * a % p;
    a = a * a % p;
    n >>= 1;
  }
  return res;
}
void work() {
  long long n;
  scanf("%lld%lld", &n, &p);
  long long tmp = 0;
  int i;
  for (i = 1; i <= n; i = ((i + 1) << 1) - 1) {
    tmp = (tmp + (i - (i >> 1)) * (tmp + 1) % p) % p;
  }
  i = ((i + 1) >> 1) - 1;
  tmp = (tmp + (n - i) * (tmp + 1) % p) % p;
  printf("%lld\n", tmp);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int T = 1;
  scanf("%d", &T);
  while (T--) {
    work();
  }
}
