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/template.hpp"
#include "../../../math/floor-sum.hpp"
int main(){
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
int t;
cin >> t;
rep(_, t){
int n,m,a,b;
cin >> n >> m >> a >> b;
cout << floor_sum(n, m, a, b) << "\n";
}
}
#line 1 "test/yosupo/Math/Sum-of-Floor-of-Linear.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/sum_of_floor_of_linear"
#line 1 "template/template.hpp"
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <algorithm>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <deque>
#include <bitset>
#include <cctype>
#include <climits>
#include <functional>
#include <cassert>
#include <numeric>
#include <cstring>
#define rep(i, n) for(int i = 0; i < (n); i++)
#define per(i, n) for(int i = (n) - 1; i >= 0; i--)
using ll = long long;
#define vi vector<int>
#define vvi vector<vi>
#define vl vector<ll>
#define pii pair<int, int>
#define pll pair<ll, ll>
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
constexpr int mod = 1000000007;
using namespace std;
template<class T, class U>
bool chmax(T &a, const U &b){ return a < b ? (a = b, 1) : 0; }
template<class T, class U>
bool chmin(T &a, const U &b){ return a > b ? (a = b, 1) : 0; }
#line 4 "test/yosupo/Math/Sum-of-Floor-of-Linear.test.cpp"
#line 1 "math/floor-sum.hpp"
using ull = unsigned long long;
ull floor_sum_unsigned(ull n, ull m, ull a, ull b){
ull ans = 0;
while(true){
if(a >= m){
ans += n * (n - 1) / 2 * (a / m);
a %= m;
}
if(b >= m){
ans += n * (b / m);
b %= m;
}
const ull y_max = a * n + b;
if(y_max < m) break;
n = y_max / m;
b = y_max % m;
swap(m, a);
}
return ans;
}
ll floor_sum(const ll n, const ll m, ll a, ll b){
assert(0 <= n && n < (1LL << 32));
assert(1 <= m && m < (1LL << 32));
ull ans = 0;
if(a < 0){
const ull a2 = (a % m + m) % m;
ans -= 1ULL * n * (n - 1) / 2 * ((a2 - a) / m);
a = a2;
}
if(b < 0){
const ull b2 = (b % m + m) % m;
ans -= 1ULL * n * ((b2 - b) / m);
b = b2;
}
return ans + floor_sum_unsigned(n, m, a, b);
}
#line 6 "test/yosupo/Math/Sum-of-Floor-of-Linear.test.cpp"
int main(){
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
int t;
cin >> t;
rep(_, t){
int n,m,a,b;
cin >> n >> m >> a >> b;
cout << floor_sum(n, m, a, b) << "\n";
}
}