题目描述
Byteasar the Cryptographer works on breaking the code of BSA (Byteotian Security Agency). He has alreadyfound out that whilst deciphering a message he will have to answer multiple queries of the form"for givenintegers aa , bb and dd , find the number of integer pairs (x,y)(x,y) satisfying the following conditions:
1\le x\le a1≤x≤a , 1\le y\le b1≤y≤b , gcd(x,y)=dgcd(x,y)=d , where gcd(x,y)gcd(x,y) is the greatest common divisor of xx and yy ".
Byteasar would like to automate his work, so he has asked for your help.
TaskWrite a programme which:
reads from the standard input a list of queries, which the Byteasar has to give answer to, calculates answers to the queries, writes the outcome to the standard output.
FGD正在破解一段密码,他需要回答很多类似的问题:对于给定的整数a,b和d,有多少正整数对x,y,满足x<=a,y<=b,并且gcd(x,y)=d。作为FGD的同学,FGD希望得到你的帮助。
输入输出格式
输入格式:The first line of the standard input contains one integer nn ( 1\le n\le 50\ 0001≤n≤50 000 ),denoting the number of queries.
The following nn lines contain three integers each: aa , bb and dd ( 1\le d\le a,b\le 50\ 0001≤d≤a,b≤50 000 ), separated by single spaces.
Each triplet denotes a single query.
Your programme should write nn lines to the standard output. The ii 'th line should contain a single integer: theanswer to the ii 'th query from the standard input.
输入输出样例
2 4 5 2 6 4 3
3 2
这题的大概题意是求满足x<=a,y<=b,并且gcd(x,y)=d的(x,y)有多少对。我们可以把d提取出来,及转化为求满足x<=a/d,y<=b/d,并且gcd(x,y)=1的(x,y)有多少对。
在这里繁琐的设函数推导过程就不在赘述了,大家可以看这篇博客是相类似的。不同的地方是这次只要求gcd(x,y)=1的对数,因此我们可以把后面的
换成u(T)即可。这样一来我们再用分块以及u函数的前缀和就能求出答案。
AC代码:
#include<cstdio>
#include<iostream>
#define ll long long
using namespace std;
const int Maxn=50005;
ll pri[Maxn],mu[Maxn],sum[Maxn],k,t;
bool vis[Maxn];
inline ll mn(ll x,ll y){
return x<y?x:y;
}
inline ll read(){//快速读入,卡常必备
ll x=0;char c=getchar();
while(c<'0'||c>'9'){c=getchar();}
while(c<='9'&&c>='0'){x=x*10;x=x+c-'0';c=getchar();}
return x;
}
void prep(){//预处理
mu[1]=1;
for(int i=2;i<=Maxn;++i){//筛素数+求莫比乌斯函数
if(!vis[i]){pri[++k]=i;mu[i]=-1;}
for(int j=1;j<=k&&pri[j]*i<=Maxn;++j){
vis[pri[j]*i]=1;
if(i%pri[j]==0)break;
mu[pri[j]*i]=-mu[i];
}
}
for(int i=1;i<=Maxn;++i){
sum[i]=sum[i-1]+mu[i];//前缀和
}
}
void work(){
ll n,m,d,x,ans=0,lim;
n=read();m=read();d=read();n/=d;m/=d;lim=mn(n,m);
for(int i=1;i<=lim;i=x+1){
x=mn(n/(n/i),m/(m/i));//分块
ans+=(n/i)*(m/i)*(sum[x]-sum[i-1]);
}
printf("%lld\n",ans);
}
int main(){
prep();
scanf("%lld",&t);
while(t--){
work();
}
return 0;
}