#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
const double epsilon = PI / 180.0;
void solve(vector<long long> &arr, long long num, long long idx, long long cnt,
           long long m, long long &res) {
  if (cnt == 0) {
    res += num;
    res %= m;
    return;
  }
  if (idx >= arr.size()) return;
  for (long long i = idx; i < arr.size(); ++i) {
    solve(arr, arr[i] * num % m, i + 1, cnt - 1, m, res);
  }
  return;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int q = 1;
  cin >> q;
  while (q--) {
    long long d, m;
    cin >> d >> m;
    vector<long long> arr = {1};
    long long sum = 1;
    while (d > sum) {
      arr.push_back(min(d - sum, arr.back() * 2));
      sum += arr.back();
    }
    long long ans = 0;
    for (int j = 1; j <= arr.size(); ++j) {
      ans = ((ans + 1) * arr[j - 1] + ans) % m;
    }
    cout << ans << endl;
  }
  return 0;
}
