#include <bits/stdc++.h>
using namespace std;
long long int mod = 1000000007;
bool check(pair<long long int, long long int> p1,
           pair<long long int, long long int> p2) {
  return p2.second > p1.second;
}
int main() {
  long long int t;
  cin >> t;
  while (t--) {
    long long int d, m;
    cin >> d >> m;
    mod = m;
    long long int count = ceil(log2(d));
    if (ceil(log2(d)) == log2(d)) {
      count = ceil(log2(d)) + 1;
    }
    long long int ans = 1 % mod;
    long long int temp = 1;
    while (temp < count - 1) {
      ans += ((long long int)(pow(2, temp))) * ans;
      ans %= mod;
      ans += ((long long int)(pow(2, temp)));
      ans %= mod;
      temp++;
    }
    long long int temp1 = d - pow(2, temp) + 1;
    ans += temp1 * ans;
    ans %= mod;
    ans += temp1;
    ans %= mod;
    if (d == 1) {
      cout << 1 % mod << endl;
    } else {
      cout << ans << endl;
    }
  }
  return 0;
}
