#include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e6 + 1;
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    long long d, m;
    cin >> d >> m;
    long long mn = 1;
    for (; (1 << (mn - 1)) <= d; mn++)
      ;
    --mn;
    vector<vector<long long> > dp(mn + 1, vector<long long>(mn, 0));
    for (long long i = 0; i < mn - 1; i++) dp[1][i] = (1 << i);
    dp[1][mn - 1] = (d == 1 ? 1 : d % (1 << (mn - 1)) + 1);
    for (long long n = 2; n <= mn; n++) {
      for (long long i = 0; i < mn; i++)
        for (long long j = 0; j < i; j++)
          dp[n][i] =
              (dp[n][i] + min((1ll << i), d - (1 << i) + 1) * dp[n - 1][j]) % m;
    }
    long long ans = 0;
    for (long long n = 1; n <= mn; n++)
      for (long long i = 0; i < mn; i++) ans = (ans + dp[n][i]) % m;
    cout << ans << '\n';
  }
  return 0;
}
