Sherlock and Watson Gym Secrets (Large)

Count ordered pairs (i, j), i != j, i, j 1..N, with i^A + j^B divisible by K, output mod 1e9+7.

Medium7Number theoryMathCombinatoricsHash mapNo attempts yetTime limit5sMemory limit512 MB

Problem

Watson and Sherlock are gym buddies.

Their gym trainer has given them three integers AA, BB, and NN, and has asked them to pick two different positive integers ii and jj, both less than or equal to NN. Watson is expected to eat exactly iAi^A sprouts every day, and Sherlock is expected to eat exactly jBj^B sprouts every day.

Watson and Sherlock have noticed that if the total number of sprouts they eat on a given day is divisible by a certain integer KK, they get along well that day.

Count the pairs (i,j)(i, j) with iji \ne j such that iA+jBi^A + j^B is divisible by KK. Pairs are ordered, so (1,2)(1, 2) and (2,1)(2, 1) are different pairs. The number of pairs can be very large, so output it modulo 109+710^9+7 (10000000071000000007).

Since ii and jj are positive, iA=1i^A = 1 when A=0A = 0, and jB=1j^B = 1 when B=0B = 0.

Input

The first line of the input gives the number of test cases, TT. TT test cases follow. Each test case consists of one line with the four integers AA, BB, NN, and KK described above.

Output

For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the required answer.

Constraints

  • 1T1001 \le T \le 100
  • 0A1060 \le A \le 10^6
  • 0B1060 \le B \le 10^6
  • 1K1000001 \le K \le 100000
  • 1N10181 \le N \le 10^{18}

Hint

In the first test case of the example, the possible pairs are (1,2)(1, 2), (1,5)(1, 5), (2,1)(2, 1), (2,4)(2, 4), (4,2)(4, 2), (4,5)(4, 5), (5,1)(5, 1), and (5,4)(5, 4).

In the second test case, the possible pairs are (1,2)(1, 2), (1,3)(1, 3), and (4,1)(4, 1).

In the third test case, no pair is possible because of the condition iji \ne j.