#include <bits/stdc++.h>
using namespace std;
long long log2(long long k) {
  if (k == 0) return 0;
  return 1 + log2(k / 2);
}
void solve() {
  long long sum = 0, prod = 1;
  long long n, ar[1000], ans = 1, d, m;
  cin >> d >> m;
  n = log2(d);
  for (int i = 1; i < n; i++) {
    ans = (ans * (prod + 1)) % m;
    sum += prod;
    prod *= 2;
  }
  ans = (ans * (d - sum + 1)) % m;
  cout << (ans - 1 + m) % m << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
