2301: [HAOI2011]Problem b
Time Limit: 50 Sec Memory Limit: 256 MBSubmit: 4854 Solved: 2257
[ 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
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
Source
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N = 50000 + 5;
int T,a,b,c,d,k,tot;
int mul[N],sum[N],pri[N];
bool isnot[N];
void init(){
mul[1] = 1;
for( int i = 2; i <= N-5; i++ ){
if( !isnot[i] ){
mul[i] = -1;
pri[++tot] = i;
}
for( int j = 1; j <= tot && i*pri[j] <= N-5; j++ ){
isnot[i*pri[j]] = true;
if( i % pri[j] == 0 ){ mul[i*pri[j]] = 0; break; }
else mul[i*pri[j]] = -mul[i];
}
}
for( int i = 1; i <= N-5; i++ )
sum[i] = sum[i-1] + mul[i];
}
int cal( int n, int m ){
if( n > m ) swap(n,m);
int res = 0, p;
for( int i = 1; i <= n; i = p+1 ){
p = min(n/(n/i),m/(m/i));
res += (sum[p]-sum[i-1])*(n/i)*(m/i);
}
return res;
}
int main(){
init();
scanf("%d", &T);
while( T-- ){
scanf("%d%d%d%d%d", &a, &b, &c, &d, &k); a--; c--;
a /= k; b /= k; c /= k; d /= k;
int ans = cal(a,c) + cal(b,d) - cal(a,d) - cal(b,c);
printf("%d\n", ans);
}
return 0;
}