This documentation is automatically generated by online-judge-tools/verification-helper
#define PROBLEM "https://judge.yosupo.jp/problem/sum_of_floor_of_linear"
#include "template.hpp"
#include "number-theory/floor-sum.hpp"
int main(){
cin.tie(nullptr)->sync_with_stdio(false);
int t;
cin >> t;
while(t--){
ll n,m,a,b;
cin >> n >> m >> a >> b;
cout << floor_sum(a,b,m,n-1) << "\n";
}
}
#line 1 "verify/yosupo/number-theory/sum_of_floor_of_linear.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/sum_of_floor_of_linear"
#line 1 "template.hpp"
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
using ll = long long;
using db = long double;
using vi = vector<int>;
using vl = vector<ll>;
using vd = vector<db>;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using pdd = pair<db,db>;
const int INF=INT_MAX/2;
const int MOD=998244353;
const int MOD2=1000000007;
const ll LINF=LLONG_MAX/2;
const db DINF=numeric_limits<db>::infinity();
const db EPS=1e-9;
const db PI=acos(db(-1));
template<class T>
using ordered_set = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
template<class T>
using ordered_multiset = tree<T,null_type,less_equal<T>,rb_tree_tag,tree_order_statistics_node_update>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count());
#line 2 "number-theory/floor-sum.hpp"
/**
* Author: Teetat T.
* Date: 2024-09-21
* Description: Floor sum function.
* $f(a, b, c, n) = \sum_{x=0}^n \lfloor \frac{ax+b}{c} \rfloor$
* becareful when a,b,c are negetive (use custom floor division and mod instead)
* Time: $O(\log a)$
*/
ll floor_sum(ll a,ll b,ll c,ll n){
ll res=n*(n+1)/2*(a/c)+(n+1)*(b/c);
a%=c,b%=c;
if(a==0)return res;
ll m=(a*n+b)/c;
return res+n*m-floor_sum(c,c-b-1,a,m-1);
}
#line 4 "verify/yosupo/number-theory/sum_of_floor_of_linear.test.cpp"
int main(){
cin.tie(nullptr)->sync_with_stdio(false);
int t;
cin >> t;
while(t--){
ll n,m,a,b;
cin >> n >> m >> a >> b;
cout << floor_sum(a,b,m,n-1) << "\n";
}
}