#include <bits/stdc++.h>
using namespace std;
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    int d, m;
    scanf("%d%d", &d, &m);
    std::vector<long long> dp(30);
    dp[0] = 2;
    for (int i = 1; i < 30; ++i) {
      dp[i] =
          (min(1 << i, max(0, d - (1 << i) + 1)) * dp[i - 1] % m + dp[i - 1]) %
          m;
    }
    printf("%lld\n", (dp[29] - 1 + m) % m);
  }
  return 0;
}
