#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long d, m;
  cin >> d >> m;
  long long temp = d;
  vector<long long> v;
  for (long long i = 1;; i *= 2) {
    if (temp <= i) {
      v.push_back(temp);
      break;
    } else {
      v.push_back(i);
      temp -= i;
    }
  }
  vector<long long> dp(v.size());
  dp[0] = 2;
  for (long long i = 1; i < v.size(); i++) {
    dp[i] = ((v[i] + 1) * (dp[i - 1])) % m;
  }
  cout << ((dp[v.size() - 1] - 1) % m + m) % m << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
}
