#include <bits/stdc++.h>
using namespace std;
void run() {
  long long n, m, dp[40];
  cin >> n >> m;
  dp[1] = 1LL;
  dp[0] = 0LL;
  for (int i = (2); i < (34); i++) {
    dp[i] =
        (((dp[i - 1] + 1) * (long long)(pow(2, i - 1))) % m + dp[i - 1]) % m;
  }
  long long pot = 0, num = n;
  while (num != 1) {
    num /= 2;
    pot++;
  }
  long long ans =
      (dp[pot] + (n - (long long)pow(2, pot) + 1) * (dp[pot] + 1)) % m;
  cout << ans << endl;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    run();
  }
  return 0;
}
