1. 程式人生 > >hdu 1695 GCD(容斥定理)

hdu 1695 GCD(容斥定理)

GCD

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4308    Accepted Submission(s): 1510


Problem Description Given 5 integers: a, b, c, d, k, you're to find x in a...b, y in c...d that GCD(x, y) = k. GCD(x, y) means the greatest common divisor of x and y. Since the number of choices may be very large, you're only required to output the total number of different number pairs.
Please notice that, (x=5, y=7) and (x=7, y=5) are considered to be the same.

Yoiu can assume that a = c = 1 in all test cases.


Input The input consists of several test cases. The first line of the input is the number of the cases. There are no more than 3,000 cases.
Each case contains five integers: a, b, c, d, k, 0 < a <= b <= 100,000, 0 < c <= d <= 100,000, 0 <= k <= 100,000, as described above.

Output For each test case, print the number of choices. Use the format in the example.

Sample Input 2 1 3 1 5 1 1 11014 1 14409 9
Sample Output Case 1: 9 Case 2: 736427 Hint
For the first sample input, all the 9 pairs of numbers are (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 5), (3, 4), (3, 5).
Source
Recommend wangye

題解:相當於求1~a和1~b之間的互質對數,假定a<=b,則1~a部分可以用尤拉函式求,a+1~b部分可以用容斥定理求

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
long long phi[100008];
int head[100008],all;
struct edge{
    int data,next;
}p[800008];
void add(int x,int y)
{
    p[all].next=head[x];
    p[all].data=y;
    head[x]=all++;
}
void init()
{
    int i,j;

    memset(phi,0,sizeof(phi));
    memset(head,-1,sizeof(head));
    for(all=0,phi[1]=1,i=2;i<=100000;i++)
    {
        if(!phi[i])
        {
            for(j=i;j<=100000;j+=i)
            {
                if(!phi[j]) phi[j]=j;
                phi[j]=phi[j]/i*(i-1);
                add(j,i);
            }
        }
        phi[i]+=phi[i-1];
    }
}
long long dfs(int x,int now)
{
    long long res=0,i;

    for(i=now;i!=-1;i=p[i].next)
        res+=x/p[i].data-dfs(x/p[i].data,p[i].next);

    return res;
}
int main()
{
    int t,x,s,e,k,i,cas=1;
    long long res;

    init();
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d%d%d",&x,&s,&x,&e,&k);
        if(k==0){ printf("Case %d: 0\n",cas++); continue; }
        if(s>e) s^=e^=s^=e;
        s=s/k,e=e/k;
        res=phi[s];
        for(i=s+1;i<=e;i++) res+=s-dfs(s,head[i]);
        printf("Case %d: %I64d\n",cas++,res);
    }

    return 0;
}