#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long x = 0;
  bool f = true;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') f = false;
    c = getchar();
  }
  while (c >= '0' && c <= '9')
    x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
  return f ? x : -x;
}
int tc;
long long d, m;
int main() {
  tc = read();
  while (tc--) {
    d = read(), m = read();
    long long ans = 0, tp = 1;
    for (register int i = 1; i <= 32; ++i) {
      if (d < (1ll << i)) {
        ans = (ans + (d - (1ll << (i - 1)) + 1) * tp) % m;
        break;
      }
      ans = (ans + (1ll << (i - 1)) * tp) % m;
      tp = tp * ((1ll << (i - 1)) + 1) % m;
    }
    printf("%lld\n", ans);
  }
  return 0;
}
