#include <bits/stdc++.h>
using namespace std;
int scan_int() {
  int x;
  if (!scanf("%d", &x)) throw 1;
  return x;
}
int f(int d, int m) {
  if (d == 1) return 1 % m;
  for (int i = 30; i >= 0; --i)
    if (d > (1 << i) - 1) {
      long long x = f((1 << i) - 1, m);
      long long y = d - ((1 << i) - 1);
      return (x + y * (x + 1)) % m;
    }
  throw 1;
}
int main() {
  int T = scan_int();
  for (int tt = 0; tt < T; ++tt) {
    int d = scan_int();
    int m = scan_int();
    printf("%d\n", f(d, m));
  }
}
