#include <bits/stdc++.h>
using namespace std;
int T;
long long d, m, ans;
long long dp[100][100];
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  ;
  cin >> T;
  while (T--) {
    cin >> d >> m;
    memset(dp, 0, sizeof(dp));
    int k = (int)log2(d);
    ans = 0;
    for (int i = 0; i <= k; i++) {
      int temp = 1 << i;
      if (i < k)
        dp[1][i] = temp;
      else
        dp[1][i] = d - temp + 1;
      ans = (ans + dp[1][i]) % m;
    }
    for (int i = 2; i <= k + 1; i++) {
      long long temp = dp[i - 1][0];
      for (int j = 1; j <= k; j++) {
        long long tmp = 1 << j;
        if (j == k) tmp = d - tmp + 1;
        dp[i][j] = (dp[i][j] + temp * tmp % m) % m;
        ans = (ans + dp[i][j]) % m;
        temp = (temp + dp[i - 1][j]) % m;
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
