#include <stdio.h>

int main() {
	int i, j;
	int k;
	int n, p;
	scanf("%d", &k);
	
	for (i = 0; i < k; i++) {
		scanf("%d%d", &n, &p);
		int owan = p;
		int child[n];
		int turn = -1;
		for (j = 0; j < n; j++) {
			child[j] = 0;
		}
		
		do {
			turn = (turn + 1) % n;
			if (owan > 0) {
				child[turn]++;
				owan--;
			} else {
				owan += child[turn];
				child[turn] = 0;
			}
		} while (child[turn] != p);
		printf("%d\n", turn);
	}
	
	return 0;
}