Sherlock and Permutation Sorting (Small)

For every permutation of 1..N, find the maximum number of order-preserving chunks with all earlier-chunk values smaller than later ones, then sum f(p)^2 modulo M.

Medium7Dynamic programmingCombinatoricsMathPrefix sumNo attempts yetTime limit5sMemory limit512 MB

Problem

Watson is curious about parallel computing. He wants to sort a permutation of the integers 1 through NN by breaking it into chunks, sorting each chunk on its own, and concatenating the sorted chunks.

For a permutation p1,p2,,pNp_1, p_2, \ldots, p_N, a chunk is a contiguous subarray: the elements pi,pi+1,,pjp_i, p_{i+1}, \ldots, p_j for indexes ii and jj with 1ijN1 \le i \le j \le N.

Watson partitions his permutation into an ordered list of one or more chunks without changing the order of the elements, so that every element belongs to exactly one chunk and every element of a chunk is smaller than every element of any later chunk. For the permutation [2, 1, 3, 5, 4] there are exactly four legal partitions:

[[2, 1, 3], [5, 4]]
[[2, 1], [3, 5, 4]]
[[2, 1], [3], [5, 4]]
[[2, 1, 3, 5, 4]]

Watson is happiest when the number of chunks is as large as possible. Write f(p)f(p) for the maximum number of chunks of a permutation pp. For the permutation above, f(p)=3f(p) = 3.

Take every permutation pp of the numbers 1 through NN and add up f(p)2f(p)^2. The sum can be large, so report it modulo MM.

Input

The first line contains the number of test cases, TT. Each of the next TT lines contains two integers NN and MM.

Output

For each test case, print one line in the form Case #x: y, where xx is the test case number starting from 1 and yy is the sum of f(p)2f(p)^2 over all permutations pp of size NN, modulo MM.

Constraints

  • 1T1001 \le T \le 100
  • 1N1001 \le N \le 100
  • 1M1091 \le M \le 10^9

MM is not always prime, and M=1M = 1 is allowed.

Explanation

For N=1N = 1 there is a single permutation and f([1])=1f([1]) = 1, so the sum of squares is 1.

For N=2N = 2 there are two permutations, f([1,2])=2f([1, 2]) = 2 and f([2,1])=1f([2, 1]) = 1, so the sum of squares is 22+12=52^2 + 1^2 = 5.

For N=3N = 3 the six permutations give f([1,2,3])=3f([1, 2, 3]) = 3, f([1,3,2])=2f([1, 3, 2]) = 2, f([2,1,3])=2f([2, 1, 3]) = 2, f([2,3,1])=1f([2, 3, 1]) = 1, f([3,1,2])=1f([3, 1, 2]) = 1 and f([3,2,1])=1f([3, 2, 1]) = 1, so the sum of squares is 32+22+22+12+12+12=203^2 + 2^2 + 2^2 + 1^2 + 1^2 + 1^2 = 20.