Sherlock and Permutation Sorting (Large)

For each N and modulus M, sum f(p)^2 over all permutations of 1..N, where f(p) is the maximum number of blocks that can be sorted independently; output the sum mod M.

Hard8Dynamic programmingCombinatoricsPrefix sumMathNo attempts yetTime limit10sMemory limit512 MB

Problem

Sherlock and Watson learned sorting in their programming course. Watson is curious about parallel computing, so he wants to sort a permutation of the integers 11 through NN by splitting it into chunks, sorting each chunk on its own, and then concatenating them.

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

Watson partitions the permutation into an ordered list of one or more chunks without changing the order of the elements. Every element belongs to exactly one chunk, and every element of a chunk is smaller than every element of every later chunk. For example, for the permutation [2,1,3,5,4][2, 1, 3, 5, 4] these are the only four legal partitions.

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

Watson is happiest when there are as many chunks as possible. Write f(p)f(p) for the maximum number of chunks of a permutation pp. In the example above that maximum is 33.

Compute the sum of f(p)2f(p)^2 over all permutations pp of the numbers 11 through NN. The sum can be large, so print it modulo MM.

Input

The first line contains the number of test cases, TT. TT test cases follow. Each test case is one line with two integers NN and MM separated by a space.

Output

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

Constraints

  • 1T201 \le T \le 20
  • 1N50001 \le N \le 5000
  • 1M1091 \le M \le 10^9

Notes

For N=1N = 1 the only permutation is [1][1] and f([1])=1f([1]) = 1, so the sum of squares is 11.

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 there are six permutations. 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, 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.

If MM is 11, the remainder is always 00.