#include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
inline void amin(T &x, U y) {
  if (y < x) x = y;
}
template <typename T, typename U>
inline void amax(T &x, U y) {
  if (x < y) x = y;
}
long long powmod(long long a, long long b) {
  long long res = 1;
  a %= 1000000007;
  assert(b >= 0);
  for (; b; b >>= 1) {
    if (b & 1) res = res * a % 1000000007;
    a = a * a % 1000000007;
  }
  return res;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    long long d, m;
    cin >> d >> m;
    if (d == 1)
      cout << (1 % m), cout << endl;
    else if (d == 2)
      cout << (3 % m), cout << endl;
    else if (d == 3)
      cout << (5 % m), cout << endl;
    else {
      long long pre_ans = 5;
      long long poww = 4;
      long long pre_ans1 = 5;
      while (poww - 1 < d) {
        pre_ans1 = pre_ans;
        pre_ans = ((pre_ans * (poww + 1)) % m + poww % m) % m;
        poww *= 2;
      }
      poww /= 2;
      poww %= m;
      cout << (((d - poww + 2) * pre_ans1) % m + (d - poww + 1) % m) % m,
          cout << endl;
    }
  }
  return 0;
}
