传送门:http://acm.timus.ru/problem.aspx?space=1&num=1797
讨论帖 膜拜各路神犇:http://www.51nod.com/question/index.html#!questionId=683
分类讨论 n>=x*y 以及 n<x*y 详见讨论帖
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;
inline char nc(){
static char buf[100000],*p1=buf,*p2=buf;
if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
return *p1++;
}
inline void read(ll &x){
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc());
}
inline ll solve(ll n,ll y,ll x){
if (x==1){
ll m=n/y;
return (m+1)*n-m*(m+1)/2*y;
}
ll a=y/x,b=y%x,m=n/y,c=(n-m*b)/x,t=n-x*c;
ll tem=c*(m+1)-m*(m+1)/2*a;
if (t>=x) tem+=solve(t,x,b)+t/x-t/b;
return tem;
}
inline ll Calc(ll n,ll x,ll y){
if (x>y) swap(x,y);
ll d=__gcd(x,y);
x/=d; y/=d; n/=d;
if (n<y) return n/x+1;
if ((long double)x*y<=n) return n-(x-1)*(y-1)/2+1;
return solve(n,y,x)+n/y+1;
}
int main(){
ll x,y,s,t,Q;
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
read(Q);
while (Q--){
read(x); read(y); read(s); read(t);
printf("%lld\n",Calc(t,x,y)-Calc(s-1,x,y));
}
return 0;
}