类欧几里得算法
\(View\) \(Code\)
#include<bits/stdc++.h> using namespace std; inline int read() { int ret=0,f=1; char ch=getchar(); while('9'<ch||ch<'0') { if(ch=='-') f=-1; ch=getchar(); } while('0'<=ch&&ch<='9') { ret=(ret<<1)+(ret<<3)+ch-'0'; ch=getchar(); } return ret*f; } inline long long readl() { long long ret=0; int f=1; char ch=getchar(); while('9'<ch||ch<'0') { if(ch=='-') f=-1; ch=getchar(); } while('0'<=ch&&ch<='9') { ret=(ret<<1)+(ret<<3)+ch-'0'; ch=getchar(); } return ret*f; } const int mod=998244353; int T; long long n,a,b,c; long long query(long long a,long long b,long long c,long long n) { if(!a) return (n+1)*(b/c)%mod; if(c<=a||c<=b) return (n*(n+1)/2%mod*(a/c)%mod+(n+1)*(b/c)%mod+query(a%c,b%c,c,n)%mod)%mod; long long m=(a*n+b)/c,ret=n*m%mod-query(c,c-b-1,a,m-1); while(ret<0) ret+=mod; return ret%mod; } int main() { T=read(); while(T--) { n=readl(); a=readl(); b=readl(); c=readl(); printf("%lld\n",query(a,b,c,n)%mod); } return 0; }