#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T>
using V = vector<T>;
template <class T, class U>
using P = pair<T, U>;
using vll = V<ll>;
using vvll = V<vll>;
template <class T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <class T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
constexpr ll MOD = 1000000007;
constexpr ll HIGHINF = (ll)1e18;
constexpr int INF = 1e9;
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int t;
  cin >> t;
  while (t-- > 0) {
    ll d, m;
    cin >> d >> m;
    int maxi = 0;
    ll tmp = 1;
    while (tmp <= d) maxi++, tmp <<= 1;
    maxi--;
    ll ans = 1;
    for (int i = 0; i < maxi; i++) {
      (ans *= (1LL << i) + 1) %= m;
    }
    (ans *= d - (1LL << maxi) + 2) %= m;
    cout << (ans - 1 + m) % m << '\n';
  }
  return 0;
}
