Problem:
Score : 100 points

Problem Statement

In this problem, you should process T testcases.

For each testcase, you are given four integers N, M, A, B.

Calculate \sum_{i = 0}^{N - 1} floor((A \times i + B) / M).

Constraints

1 \leq T \leq 100,000

1 \leq N, M \leq 10^9

0 \leq A, B < M

Input

Input is given from Standard Input in the following format:

T
N_0 M_0 A_0 B_0
N_1 M_1 A_1 B_1
:
N_{T - 1} M_{T - 1} A_{T - 1} B_{T - 1}

Output

Print the answer for each testcase.

Sample Input 1

5
4 10 6 3
6 5 4 3
1 1 0 0
31415 92653 58979 32384
1000000000 1000000000 999999999 999999999

Sample Output 1

3
13
0
314095480
499999999500000000

Solution in Lua (Lua 5.3.5) (judge verdict: Accepted)

-- 5.3
-- Sum_{i=0}^{n-1} floor{(a * i + b) / b}
local function floorSum(n, m, a, b)
  local ans = 0
  while true do
    if m <= a then
      ans = ans + ((n - 1) * n // 2) * (a // m)
      a = a % m
    end
    if m <= b then
      ans = ans + n * (b // m)
      b = b % m
    end
    local ymax = (a * n + b) // m
    local xmax = ymax * m - b
    if ymax == 0 then break end
    ans = ans + (n - (xmax + a - 1) // a) * ymax
    n, m, a, b = ymax, a, m, (a - xmax % a) % a
  end
  return ans
end

local q = io.read("*n")
for i = 1, q do
  local n, m, a, b = io.read("*n", "*n", "*n", "*n")
  print(floorSum(n, m, a, b))
end