Crop Triangles (Large)

Generate n points with a given recurrence and count triples whose coordinate sums are divisible by 3 on both axes.

Medium6MathCombinatoricsHash mapNo attempts yetTime limit5sMemory limit512 MB

Problem

A few pranksters have watched too much of the documentary channel, so they decided to build a crop triangle overnight. The stage is a wide field that looks like an evenly spaced grid from above. Some trees are planted in the field, and every tree stands on a point where two grid lines meet (a grid point). The pranksters want the three vertices of their triangle to sit on trees. To make it more interesting, they also want the centroid of the triangle to land on a grid point. For a triangle with vertices (x1,y1)(x_1, y_1), (x2,y2)(x_2, y_2) and (x3,y3)(x_3, y_3), the centroid is (x1+x2+x33,y1+y2+y33)\left(\frac{x_1 + x_2 + x_3}{3}, \frac{y_1 + y_2 + y_3}{3}\right).

You are given the integer coordinates of every tree in the field. Count the triangles formed by three distinct trees whose centroid has integer coordinates in both axes.

If the three trees are collinear the area is 0, and such a triangle still counts.

Input

The first line contains the number of test cases NN. NN test cases follow. Each test case is one line holding the integers nn, AA, BB, CC, DD, x0x_0, y0y_0 and MM, separated by exactly one space. nn is the number of trees.

The coordinates of the trees come out in the order the following pseudocode prints them. mod is the remainder operation.

X = x0, Y = y0
print X, Y
for i = 1 to n-1
  X = (A * X + B) mod M
  Y = (C * Y + D) mod M
  print X, Y

The parameters are chosen so that no coordinate appears twice.

Limits

  • 1N101 \le N \le 10
  • 0A,B,C,D,x0,y01090 \le A, B, C, D, x_0, y_0 \le 10^9
  • 1M1091 \le M \le 10^9
  • 3n1000003 \le n \le 100000

Output

For each test case, print one line starting with Case #X: , where XX is the test case number starting from 1. Follow it with the integer number of triangles that have three distinct trees as vertices and a centroid on a grid point.

Hint

In the first test case of the example input, the four trees that are generated are (0,1)(0, 1), (7,3)(7, 3), (17,5)(17, 5) and (17,7)(17, 7).