import java.math.BigInteger; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args){ Scanner cin = new Scanner(System.in); int T = cin.nextInt(); while(T-- > 0) { BigInteger x = cin.nextBigInteger(), y = cin.nextBigInteger(), t, z; t = x.subtract(BigInteger.valueOf(1)); //System.out.println(t); z = x.subtract(BigInteger.valueOf(2)); x = z.multiply(t).divide(BigInteger.valueOf(2)).mod(y); System.out.println(x); } cin.close(); } }