HDU4135 Co-prime
? 解题记录 ? ? 容斥 ? ? HDU ?    2018-08-21 11:19:44    597    0    0
Problem Description
Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.

Input
The first line on input contains T (0 < T <= 100) the number of test cases, each of the next T lines contains three integers A, B, N where (1 <= A <= B <= 1015) and (1 <=N <= 109).

Output
For each test case, print the number of integers between A and B inclusive which are relatively prime to N. Follow the output format below.

Sample Input
```2
1 10 2
3 15 5```

Sample Output
```Case #1: 5
Case #2: 10```

Hint

In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.

Source

Recommend
lcy   |   We have carefully selected several similar problems for you:  1796 1434 3460 1502 4136

## 简单容斥，考虑枚举n的质因数，容斥出不能被其中任何一个质因数整除的数。分析复杂度：2*3*5*7*11*13*17*19*23*29刚好超过2e9，这时候只有10个数，一次的复杂度也就是O(1000)，显然是轻松可过的。

```#include<cstdio>
#include<cstring>
#include<cmath>
#define LL long long
using namespace std;
LL a[12], ans;
LL gcd(LL a, LL b) {
return b ? gcd(b, a % b) : a;
}
void GetAns(int step, LL cnt, LL m, int rw) {
if(cnt > m) return;
if(step == (*a) + 1) {
ans += (m / cnt) * rw;
return ;
}
GetAns(step + 1, cnt * a[step] / gcd(a[step], cnt), m, rw * (-1));
GetAns(step + 1, cnt, m, rw);
}

LL solve(LL n, LL m) {
*a = 0, ans = 0;
LL sqt = (LL)sqrt(n);
for(register int i = 2; i <= n && i <= sqt; ++i) {
if(n % i == 0) a[++(*a)] = i;
while(n % i == 0) n /= i;
}
if(n != 1) a[++(*a)] = n;
GetAns(1, 1, m, 1);
return ans;
}

LL u, l, r, t;
int main() {
scanf("%d", &t);
for(register int cs = 1; cs <= t; ++cs) {
scanf("%lld%lld%lld", &l, &r, &u);
printf("Case #%d: %lld\n", cs, solve(u, r) - solve(u, l - 1));
}
return 0;
}```

597 人读过

0 条评论