#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long d, MOD;
    cin >> d >> MOD;
    vector<long long> num;
    long long k = d;
    long long n = 0;
    long long c = 1;
    while (c <= k) {
      if (c * 2 > k) {
        num.push_back(d - c + 1);
      } else {
        num.push_back(c);
      }
      c *= 2;
    }
    n = num.size();
    long long dp_1[40];
    long long dp_2[40];
    long long ans = 0;
    for (long long i = 0; i < 40; ++i) dp_1[i] = dp_2[i] = 0;
    for (long long i = 0; i < num.size(); ++i) {
      ans += num[i];
      ans %= MOD;
      dp_1[i] = num[i];
    }
    for (long long i = 1; i < n; ++i) {
      long long sum = dp_1[0];
      for (long long j = 1; j < n; ++j) {
        dp_2[j] = sum * num[j] % MOD;
        ans += dp_2[j];
        ans %= MOD;
        sum += dp_1[j];
      }
      for (long long i = 0; i < n; ++i) {
        dp_1[i] = dp_2[i];
        dp_2[i] = 0;
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
