#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  ;
  while (t--) {
    long long d, m;
    cin >> d >> m;
    if (d == 1) {
      cout << 1 % m << "\n";
      continue;
    }
    if (d == 2) {
      cout << 3 % m << "\n";
      continue;
    }
    vector<long long> p{1 % m, 3 % m};
    long long i = 2;
    long long prev = 1 % m;
    while ((1LL << i) <= d) {
      long long dst = ((1LL << (i - 1)) - 1 + m) % m;
      prev = (dst * (prev + 1) + p.back()) % m;
      long long nxt = (2 * prev + 1) % m;
      p.push_back(nxt);
      ++i;
    }
    long long dst = (d - (1LL << (i - 1))) % m;
    long long nxt = (dst * (prev + 1) + p.back()) % m;
    cout << nxt << "\n";
  }
  return 0;
}
