#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
  int d, M;
  cin >> d >> M;
  vector<ll> dp(30);
  dp[0] = 2;
  for (int i = 1; i < 30; ++i) {
    dp[i] =
        (min(1 << i, max(0, d - (1 << i) + 1)) * dp[i - 1] % M + dp[i - 1]) % M;
  }
  cout << (dp[29] - 1 + M) % M << '\n';
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
}
