2301: [HAOI2011]Problem b

2301: [HAOI2011]Problem b

Time Limit: 50 Sec  Memory Limit: 256 MB
Submit: 4164  Solved: 1888
[Submit][Status][Discuss]

Description

 

对于给出的n个询问,每次求有多少个数对(x,y),满足a≤x≤b,c≤y≤d,且gcd(x,y) = k,gcd(x,y)函数为x和y的最大公约数。



Input

第一行一个整数n,接下来n行每行五个整数,分别表示a、b、c、d、k

 

Output

共n行,每行一个整数表示满足要求的数对(x,y)的个数

 

Sample Input

2

2 5 1 5 1

1 5 1 5 2



Sample Output


14

3



HINT

 



100%的数据满足:1≤n≤50000,1≤a≤b≤50000,1≤c≤d≤50000,1≤k≤50000


#include<cstdio>
#include<iostream>
using namespace std;
const int N=5e4+10;
int a,b,c,d,k,tot,T,mu[N],prime[N],sum[N];
bool check[N]={1,1};
void pre(){
    mu[1]=1;int n=5e4;
    for(int i=2;i<=n;i++){
        if(!check[i]) prime[++tot]=i,mu[i]=-1;
        for(int j=1;j<=tot&&i*prime[j]<=n;j++){
            check[i*prime[j]]=1;
            if(i%prime[j]==0){mu[i*prime[j]]=0;break;}
            else mu[i*prime[j]]=-mu[i];
        }
    }
    for(int i=1;i<=n;i++) sum[i]=sum[i-1]+mu[i];
}
int calc(int n,int m){
    if(n>m) swap(n,m);
    int ans=0,pos=0;
    for(int i=1;i<=n;i=pos+1){
        pos=min(n/(n/i),m/(m/i));
        ans+=(n/i)*(m/i)*(sum[pos]-sum[i-1]);
    }
    return ans; 
} 
int main(){
    pre();
    for(scanf("%d",&T);T--;){
        scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
        a--,c--;
        int ans=calc(b/k,d/k)-calc(a/k,d/k)-calc(c/k,b/k)+calc(a/k,c/k);
        printf("%d\n",ans);
    }
    return 0;
}

 

 

posted @ 2017-01-09 22:03  神犇(shenben)  阅读(182)  评论(0编辑  收藏  举报