public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int m = s.nextInt();
for (int i = 0 ; i < m ; i ++){
long n = s.nextLong() , k = s.nextLong();
if(k == 2) System.out.println(1);
else if(k == 4){
long p = 1;
if(n >= 2) p += n - 2 + 1;
if(n >= 3) p += n - 3;
System.out.println(p);
}else if(k >= 5){
long p = 1;
if(n >= 2) p += n - 2 + 1 + 1;
if(n >= 3) p += n - 3 + 1;
System.out.println(p);
}else System.out.println(0);
}
}
}