#include <bits/stdc++.h>
using namespace std;
const int N = 10000;
void solve() {
  long long int d, m;
  cin >> d >> m;
  long long int crt = 0, x = 1;
  vector<long long int> v;
  while (crt < d) {
    crt += x;
    v.push_back(x);
    x *= 2;
  }
  auto it = v.end();
  it--;
  v.erase(it);
  x /= 2;
  crt -= x;
  v.push_back(d - crt);
  long long int ans = 1;
  for (auto X : v) {
    ans = (ans * (X + 1)) % m;
  }
  ans--;
  ans = (ans + 2 * m) % m;
  cout << ans << "\n";
}
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  srand(time(NULL));
  ;
  long long int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
}
