Linear Congruential Generator

Time limit2sMemory limit512 MB

Summary
Given a linear congruential generator and two index ranges, sum X_i mod (X_j+1) over all pairs i in the first range and j in the second.
Level

Hard9 of 10

Topics
Math, Number theory, Prefix sum, Implementation
Solved
No attempts yet

Problem

You are given a generator defined by the recurrence relation

Xn+1=((aXn+c) mod m)X_{n+1} = ((a X_n + c) \bmod {m})

where X={Xn}n=0∞X = \{X_n\}_{n=0}^{\infty} is the generated sequence of pseudorandom values, and mm, aa, cc, X0X_0 are integer constants which specify the generator.

Additionally, two integer intervals [l1,r1][l_1, r_1] and [l2,r2][l_2, r_2] are given. Please calculate

∑i=l1r1∑j=l2r2(Xi mod (Xj+1))\sum_{i=l_1}^{r_1}\sum_{j=l_2}^{r_2}(X_i \bmod {(X_j + 1)})

Input

The input contains several test cases. The first line contains an integer TT indicating the number of test cases. The following describes all test cases. For each test case:

The only line contains eight integers mm, aa, cc, X0X_0, l1l_1, r1r_1, l2l_2, r2r_2.

Output

For each test case, output a line containing “Case #x: y” (without quotes), where x is the test case number starting from 1, and y is the answer to this test case.

Constraints

  • 1≤T≤1051 \le T \le 10^5
  • 1≤m≤1061 \le m \le 10^6
  • 0≤a,c,X0<m0 \le a, c, X_0 < m
  • 0≤l1≤r1≤1060 \le l_1 \le r_1 \le 10^6
  • 0≤l2≤r2≤1060 \le l_2 \le r_2 \le 10^6
  • The sum of mm in all test cases does not exceed 2×1062 \times 10^6.

Hint

In the first sample case, X={Xn}n=0∞={1,5,2,6,3,0,… }X = \{X_n\}_{n=0}^{\infty} = \{1, 5, 2, 6, 3, 0, \dots\}.

In the second sample case, X={Xn}n=0∞={1,9,3,5,… }X = \{X_n\}_{n=0}^{\infty} = \{1, 9, 3, 5, \dots\}.

Examples1

  1. Example 1

    Input
    2
    7 1 4 1 2 3 4 5
    10 3 6 1 2 3 1 2
    
    Expected output
    Case #1: 4
    Case #2: 12