#include <iostream>
#include <fstream>

using namespace std;

long long pow2(int e, int mod)
{
	long long res = 0;
	if (e == 0)
		res = 1;
	else if (e == 1)
		res = 2;
	else if (e % 2 == 0)
	{
		long long halfExp = pow2(e/2, mod);
		res = halfExp * halfExp;
	}
	else
	{
		long long halfExpMinus1 = pow2(e/2, mod);
		res = ((halfExpMinus1 * halfExpMinus1) % mod) * 2;
	}

	return res % mod;
}

// =========== slow version ==============
// For checking purposes only
long long brute(long long n, long long m)
{
	long long res = 0;
	for (long long k = 0;k < n;k++)
		res += (((k*k)%m)*pow2(k, m)) % m;
	return res % m;
}

long long norm(long long x, long long m)
{
	if (x < 0)
		return (x - (x / m - 1)*m)%m;
	return x%m;
}

// =========== fast version ================
// Explanation follows:
// Let's S[n] be required sum up to n.
// then one can expand sum S[n+1] as follows:
//		S[n] + n*n*(2^n) = S[n+1], then express S[n+1] 
// (from the right side) through S[n], so
// you'll get the form:
//		S[n] + n*n*(2^n) = A*S[n] + B,
// where A and B should be similarly solved.
// Then you can solve this equation regarding S[n] and get a closed form solution.
// The following function represents this solution.
long long calc_sum(long long n, long long m)
{
	long long a, b, x, y, z;
	a = ((n-1)*pow2(n+1, m) + 2)%m - (n*pow2(n, m))%m;
	a = norm(a, m);

	b = (pow2(n,m) - 1L)%m;

	x = ((n*n)%m) * pow2(n, m);
	y = 4*a;
	z = 2*b;

	long long res = x%m - y%m - z%m;
	return norm(res, m);
}

int main()
{
	ifstream in("estimation.in");
	int tc;
	in >>tc;
	while (tc--)
	{
		int n, mod;
		in >>n >>mod;
		cout <<calc_sum(n, mod) <<endl;
	}
	
	return 0;
}
