#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
const long long MAX = 100005;
const long double PI = 3.14159265359;
const long double G = 9.807;
const long long INF = 1e18;
const long double EPS = 1e-6;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
bool isprime(long long a) {
  if (a == 2) return 1;
  if (!(a & 1)) return 0;
  for (long long i = 3; i * i <= a; i += 2)
    if (a % i == 0) return 0;
  return 1;
}
long long mpow(long long base, long long exponent, long long modulus) {
  if (modulus == 1) return 0;
  long long result = 1;
  base = base % modulus;
  while (exponent) {
    if (exponent % 2 == 1) result = (result * base) % modulus;
    exponent = exponent >> 1;
    base = (base * base) % modulus;
  }
  return result;
}
long long minv(long long a, long long mod) {
  long long _gcd = gcd(a, mod);
  assert(_gcd == 1);
  return mpow(a, mod - 2, mod);
}
long long t;
long long dp[35];
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> t;
  while (t--) {
    long long d, mod;
    cin >> d >> mod;
    long long temp = d;
    long long mxb = 0;
    memset(dp, 0, sizeof dp);
    for (long long i = 0; i <= 32; ++i) {
      long long p = (1LL << i);
      if (p > temp) {
        mxb = i;
        break;
      }
    }
    long long ans = 1 % mod;
    dp[1] = 1 % mod;
    for (long long i = 2; i <= mxb; ++i) {
      long long nums = mpow(2LL, i - 1, mod);
      if (i == mxb) {
        nums = d - mpow(2LL, i - 1, mod) + 1;
        nums += mod;
        nums %= mod;
      }
      dp[i] += nums;
      dp[i] %= mod;
      for (long long j = i - 1; j >= 1; --j) {
        dp[i] += dp[j] * nums % mod;
        dp[i] %= mod;
      }
      ans += dp[i];
      ans %= mod;
    }
    cout << ans << '\n';
  }
  return 0;
}
