#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
int T;
int d, n;
long long m;
long long a[40], f[40][40], ans = 0;
int main() {
  scanf("%d", &T);
  while (T--) {
    scanf("%d%lld", &d, &m);
    ans = 0;
    n = log2(d + 1);
    for (int i = 1; i <= 30; i++)
      for (int j = 1; j <= 30; j++) f[i][j] = 0;
    a[1] = 1;
    for (int i = 2; i <= n + 1; i++) a[i] = (a[i - 1] * 2) % m;
    f[1][1] = 1;
    f[n + 1][1] = d;
    for (int i = 1; i <= n + 1; i++) f[i][0] = 1;
    for (int i = 2; i <= n; i++)
      for (int j = 1; j <= i; j++)
        f[i][j] = (f[i - 1][j] + (f[i - 1][j - 1] * a[i]) % m) % m;
    int kk = d - a[n + 1] + 1;
    for (int i = 2; i <= n + 1; i++)
      f[n + 1][i] = (f[n][i] + (f[n][i - 1] * kk) % m) % m;
    for (int i = 1; i <= n + 1; i++) {
      ans += f[n + 1][i];
      ans %= m;
    }
    cout << ans << endl;
  }
  return 0;
}
