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