#define PROBLEM "https://judge.yosupo.jp/problem/sum_of_floor_of_linear"
#include"template.hpp"
#include"number-theory/floor-sum.hpp"intmain(){cin.tie(nullptr)->sync_with_stdio(false);intt;cin>>t;while(t--){lln,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 2 "template.hpp"
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>usingnamespacestd;usingnamespace__gnu_pbds;usingll=longlong;usingdb=longdouble;usingvi=vector<int>;usingvl=vector<ll>;usingvd=vector<db>;usingpii=pair<int,int>;usingpll=pair<ll,ll>;usingpdd=pair<db,db>;constintINF=INT_MAX/2;constintMOD=998244353;constintMOD2=1000000007;constllLINF=LLONG_MAX/2;constdbDINF=numeric_limits<db>::infinity();constdbEPS=1e-9;constdbPI=acos(db(-1));template<classT>usingordered_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;template<classT>usingordered_multiset=tree<T,null_type,less_equal<T>,rb_tree_tag,tree_order_statistics_node_update>;mt19937rng(chrono::steady_clock::now().time_since_epoch().count());mt19937_64rng64(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)$
*/llfloor_sum(lla,llb,llc,lln){llres=n*(n+1)/2*(a/c)+(n+1)*(b/c);a%=c,b%=c;if(a==0)returnres;llm=(a*n+b)/c;returnres+n*m-floor_sum(c,c-b-1,a,m-1);}#line 4 "verify/yosupo/number-theory/sum_of_floor_of_linear.test.cpp"
intmain(){cin.tie(nullptr)->sync_with_stdio(false);intt;cin>>t;while(t--){lln,m,a,b;cin>>n>>m>>a>>b;cout<<floor_sum(a,b,m,n-1)<<"\n";}}