#include #include using namespace std; using namespace atcoder; typedef long long int ll; typedef long double ld; typedef vector vi; typedef vector vl; typedef vector vvl; typedef vector vvvl; typedef vector vvvvl; typedef vector vb; typedef vector vvb; typedef vector vvvb; typedef vector vvvvb; typedef pair pl; typedef pair ppl; typedef pair pppl; typedef pair pppppl; #define rep(i,a,b) for(int i=(a);i<(b);i++) #define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--) #define all(a) begin(a),end(a) #define sz(a) (int)(a).size() #define F first #define S second #define bs(A,x) binary_search(all(A),x) #define lb(A,x) (ll)(lower_bound(all(A),x)-A.begin()) #define ub(A,x) (ll)(upper_bound(all(A),x)-A.begin()) #define cou(A,x) (ll)(upper_bound(all(A),x)-lower_bound(all(A),x)) templateusing min_priority_queue=priority_queue,greater>; templatebool chmax(T&a,T b){if(abool chmin(T&a,T b){if(b vm; typedef vector vvm; typedef vector vvvm; typedef vector vvvvm; ostream&operator<<(ostream&os,mint a){os<>(istream&is,mint&a){int x;is>>x;a=mint(x);return is;} //*/ templateostream&operator<<(ostream&os,pairp){os<istream&operator>>(istream&is,pair&p){is>>p.F>>p.S;return is;} templateostream&operator<<(ostream&os,vectorv){rep(i,0,sz(v))os<istream&operator>>(istream&is,vector&v){for(T&in:v)is>>in;return is;} ll f(ll N,ll M,ll A,ll B,ll C,ll D){ assert(0=0&&B>=0)return (N-1)*A+(C*(N-1)+D)/M*B; if(C==0)return max(0ll,A*(N-1)); if(B>0){ ll _N=(C*(N-1)+D)/M+1; ll _M=C; ll _A=B; ll _B=A; ll _C=M; ll _D=C-1-D; ll r=_D%_M; if(r<0)r+=_M; ll pad=(_D-r)/_M*_B; _D=r; r=_C/_M; _C%=_M; _A+=_B*r; pad+=_A; _N--; _D+=_C; if(_D>=_M)pad+=_B,_D-=_M; return max(0ll,f(_N,_M,_A,_B,_C,_D)+pad); } else{ ll _N=(C*(N-1)+D)/M; ll _M=C; ll _A=B; ll _B=A; ll _C=M; ll _D=M-1-D; ll r=_D%_M; if(r<0)r+=_M; ll pad=(_D-r)/_M*_B; _D=r; r=_C/_M; _C%=_M; _A+=_B*r; return max(A*(N-1)+(C*(N-1)+D)/M*B,f(_N,_M,_A,_B,_C,_D)+pad); } } int main(){ cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); ll _;cin>>_; while(_--){ ll N,M,A,B,C,D;cin>>N>>M>>A>>B>>C>>D; cout<