This page is still under construction.

Parts of this page are still being built. What you see may change.

Hashing

Time limit2sMemory limit128 MB

Summary
Count how many of n+1 values of a linear hash modulo m land in an interval [c, d].
Level

Medium7 of 10

Topics
Math, Number theory, Binary search
Solved
No attempts yet

Problem

Sanggeun built a hashing function that maps an integer to a value in 00 through m−1m-1:

h(y)=(a⋅y+b) mod mh(y) = (a \cdot y + b) \bmod m

Given integers xx, nn, cc, and dd, write a program that counts how many of the hash values

h(x), h(x+1), …, h(x+n)h(x),\ h(x+1),\ \dots,\ h(x+n)

fall within the interval [c,d][c, d].

Input

The first line contains the number of test cases tt (1≤t≤1051 \le t \le 10^{5}).

Each of the next tt lines contains the integers aa, bb, xx, nn, cc, dd, mm separated by spaces.

  • 1≤m≤10151 \le m \le 10^{15}
  • 0≤c≤d<m0 \le c \le d < m
  • 0≤a,b<m0 \le a, b < m
  • 0≤x+n≤10150 \le x + n \le 10^{15}
  • a⋅(x+n)+b≤1015a \cdot (x + n) + b \le 10^{15}

Every number in the input is a non-negative integer.

Output

For each test case, output on its own line the number of indices ii (0≤i≤n0 \le i \le n) satisfying c≤(a⋅(x+i)+b) mod m≤dc \le (a \cdot (x + i) + b) \bmod m \le d.

Examples3

  1. Example 1

    Input
    2
    2 3 1 3 0 1 7
    1 0 0 8 0 8 9
    
    Expected output
    1
    9
    
  2. Example 2

    Input
    1
    0 5 100 10 5 5 13
    
    Expected output
    11
    
  3. Example 3

    Input
    1
    7 3 2 50 0 10 11
    
    Expected output
    51