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 Rust (1.42.0) (judge verdict: Accepted)

use proconio::{fastout, input};

pub fn floor_sum(n: i64, m: i64, a: i64, b: i64) -> i64 {
    let mut ret = 0;
    let (mut a, mut b) = (a, b);

    if a >= m {
        ret += (n - 1) * n * (a / m) / 2;
        a %= m;
    }
    if b >= m {
        ret += n * (b / m);
        b %= m;
    }

    let y_max = (a * n + b) / m;
    let x_max = y_max * m - b;
    if y_max == 0 {
        ret
    } else {
        ret += (n - (x_max + a - 1) / a) * y_max;
        ret += floor_sum(y_max, a, m, (a - x_max % a) % a);
        ret
    }
}

#[fastout]
fn main() {
    input! {
        t: usize,
        nmab: [(usize, usize, usize, usize); t],
    }
    for (n, m, a, b) in nmab {
        let ans = floor_sum(n as i64, m as i64, a as i64, b as i64);
        println!("{}", ans);
    }
}