#include <fstream>
#include <vector>
#include <cstdio>
#include <assert.h>
#include <iostream>

using namespace std;

int main()
{
    ifstream cin("hat.in");
    ofstream cout("hat.out");
    vector<char> a(1);
    for (int i = 0; i < 27; i++)
    {
    	int si = a.size();
    	a.reserve(2 * si);
    	for (int i = 0; i < si; i++)
    		a.push_back(a[i] + 1);    			
    } 
    cerr << a.size();
    int t;
    cin >> t;
    
    for (int i = 0; i < t; i++)
    {
        long long n, p;
        cin >> n >> p;
        assert(n <= 1e7);
        cout << a[n - 1] % p << "\n";
    }
}
