#include <bits/stdc++.h>
using namespace std;
inline void fastio() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
}
const long long maxN = 35;
void solve() {
  long long n, mod;
  cin >> n >> mod;
  vector<long long> cnt(maxN);
  for (long long i = 0; i < maxN; ++i) {
    if ((1 << i) > n) break;
    long long fst = (1 << i);
    long long snd = (1 << (i + 1)) - 1;
    snd = min(n, snd);
    cnt[i] = snd - fst + 1;
    cnt[i] %= mod;
  }
  vector<long long> dp(maxN, 0);
  dp[0] = cnt[0];
  for (long long i = 0; i < maxN; ++i) {
    if ((1 << i) > n) break;
    dp[i] = cnt[i];
    for (long long j = 0; j < i; ++j) {
      dp[i] += dp[j] * cnt[i];
      dp[i] %= mod;
    }
  }
  long long ans = 0;
  for (long long i = 0; i < maxN; ++i) {
    if ((1 << i) > n) break;
    ans += dp[i];
    ans %= mod;
  }
  cout << ans << '\n';
}
signed main() {
  fastio();
  long long t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
