#include <bits/stdc++.h>
using namespace std;
const long long int mod = 1e9 + 7;
const int inf = 1e9;
const int N = 2e5;
void solve() {
  long long int d, m;
  cin >> d >> m;
  long long int mx;
  for (long long int i = 32; i >= 0; i--) {
    if ((1LL << i) & d) {
      mx = i;
      break;
    }
  }
  long long int dp[mx + 1];
  dp[mx] = (d - (1LL << mx) + 1);
  long long int res = dp[mx];
  res %= m;
  for (long long int i = mx - 1; i >= 0; i--) {
    dp[i] = (1LL << i) * (1 + res);
    res += dp[i];
    res %= m;
  }
  cout << res << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
