# [51nod2583]数论只会Gcd

$(a,b)->(a+b,b)$

$(a,b)->(a,a+b)$

$((a,b),(c,d))->((a+c,b+d),(b,d))$

$((a,b),(c,d))->((a,b),(a+c,b+d))$

#include<bits/stdc++.h>
using namespace std;
const int N=2e6+10;
typedef long long ll;

int gi() {
int x=0,o=1;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
if(ch=='-') o=-1,ch=getchar();
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x*o;
}

int mu[N],smu[N],m;
map<int,int> M;
ll ans;

int getsmu(int n) {
if(n<N) return smu[n];
if(M.count(n)) return M[n];
int ret=1;
for(int i=2,j;i<=n;i=j+1) {
j=n/(n/i);ret-=(j-i+1)*getsmu(n/i);
}
return M[n]=ret;
}

ll cal(ll n,ll a,ll b,ll c) {
if(n<0) return 0;
if(!a) return (b/c)*(n+1);
if(a>=c||b>=c) return cal(n,a%c,b%c,c)+n*(n+1)/2*(a/c)+(n+1)*(b/c);
ll m=(a*n+b)/c;
return n*m-cal(m-1,c,c-b-1,a);
}

ll cal(int x,int y,int n) {
return cal(n/x-1,x,n%x,y);
}

int main() {
mu[1]=1;
for(int i=1;i<N;i++)
for(int j=i+i;j<N;j+=i) mu[j]-=mu[i];
for(int i=1;i<N;i++) smu[i]=smu[i-1]+mu[i];
int T=gi();m=gi();
while(T--) {
int x=gi(),y=gi();
if(x>m||y>m) cout<<"0\n";
else if(x<=y) cout<<"1\n";
else {
y+=x;
if(y>m) cout<<"2\n";
else {
ans=4;
for(int i=1,j;i<=m;i=j+1) {
j=m/(m/i);ans+=4ll*(getsmu(j)-getsmu(i-1))*cal(x,y,m/i);
}
cout<<ans<<'\n';
}
}
}
return 0;
}

posted @ 2020-01-31 14:28  newbiegcz  阅读(598)  评论(4编辑  收藏