#include <bits/stdc++.h>
using namespace std;
long long int mod(long long int x) { return x % 1000000007; }
long long int power(long long int x, long long int y, long long int p) {
  long long int res = 1;
  x = x % p;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
long long int mod(long long int num, long long int den) {
  return mod(mod(num) * power(den, 1000000007 - 2, 1000000007));
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int t;
  cin >> t;
  while (t--) {
    long long int n, m;
    cin >> n >> m;
    vector<long long int> arr(32);
    arr[0] = 1;
    long long int total = floor(log(n) / log(2)) + 1;
    for (long long int i = 0; i < 32; ++i) {
      long long int val = 1 << i;
      if (i + 1 < total)
        arr[i] = val;
      else {
        arr[i] = n - val + 1;
        break;
      }
    }
    vector<long long int> dp(32);
    dp[0] = 1;
    for (long long int i = 1; i < 32; ++i) {
      dp[i] =
          (dp[i - 1] % m + (arr[i] % m) * (dp[i - 1] % m) + (arr[i] % m)) % m;
    }
    cout << dp[31] << endl;
  }
}
