题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4135
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

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

Problem solving report:

Description: 给一个区间[a,b]和一个数n,让你求出[a,b]中与n互质的数的个数。
Problem solving: 欧拉函数得到的是小于n与n互质的个数,这里是个区间。由于区间较大,不可能对[a,b]进行遍历,考虑计算区间[1,a-1]中与n互质的个数num1,[1,b]中与n互质的个数num2,最终结果就是两者相减的结果。
现在考虑如何计算区间[1,m]中n互质的个数num,num等于(m-与n不互质的个数)。
与n不互质的数就是[1,m]中n的素因子的倍数。
例如m = 12,n = 30的情况。
30的素因子数为2、3、5。
[1,12]中含有2的倍数的有:(2、4、6、8、10、12) = n/2 = 6个
[1,12]中含有3的倍数的有:(3、6、9、12) = n/3 = 4个
[1,12]中含有5的倍数的有:(5、10) = n/5 = 2个
与n不互质的数个数就是上边三个集合取并集的部分。这里用到了容斥定理,用队列数组,来实现容斥定理。

Accepted Code:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 105;
const int MAXM = 10005;
typedef long long ll;
ll fact[MAXN], Q[MAXM], cnt;
void Divid(int n) {
    cnt = 0;
    for (int i = 2; i <= n / i; i++) {
        if (!(n % i)) {
            fact[cnt++] = i;
            while (!(n % i))
                n /= i;
        }
    }
    if (n != 1)
        fact[cnt++] = n;
}
ll Reject(ll n) {
    ll ans = 0;
    int l, top = 0;
    Q[top++] = -1;
    for (int i = 0; i < cnt; i++) {
        l = top;
        for (int j = 0; j < l; j++)
            Q[top++] = -1 * Q[j] * fact[i];
    }
    for (int i = 1; i < top; i++)
        ans += n / Q[i];
    return ans;
}
int main() {
    ll l, r;
    int t, n, kase = 0;
    scanf("%d", &t);
    while (t--) {
        scanf("%lld%lld%d", &l, &r, &n);
        Divid(n);
        printf("Case #%d: %lld\n", ++kase, r - Reject(r) - (l - 1 - Reject(l - 1)));
    }
    return 0;
}