#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long int d, m;
    cin >> d >> m;
    int bits = log2(d);
    vector<vector<long long>> dp(bits + 1, vector<long long>(bits + 1, 0));
    for (int i = 0; i <= bits; i++) {
      if (i != bits)
        dp[0][i] = ((1ll << (i + 1)) - 1) % m;
      else {
        dp[0][i] = d % m;
      }
    }
    long long ans = dp[0][bits];
    for (int i = 1; i <= bits; i++) {
      for (int j = i; j <= bits; j++) {
        if (j != bits)
          dp[i][j] =
              ((dp[i - 1][j - 1] * ((1ll << (j)) % m)) % m + dp[i][j - 1]) % m;
        else {
          dp[i][j] =
              ((dp[i - 1][j - 1] * (d - (1ll << (j)) + 1)) % m + dp[i][j - 1]) %
              m;
        }
      }
      ans += dp[i][bits];
      ans %= m;
    }
    cout << ans << "\n";
  }
}
