HDU 4135 Co-prime (容斥)

来源:互联网 发布:反转链表 java 编辑:程序博客网 时间:2024/06/05 22:30

Co-prime

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5708 Accepted Submission(s): 2290

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}.

题意

求A到B之间有多少个数和N互质

思路

我们要求互质可以先求A到B之间有几个数和N不互质,和N不互质的数只要是N因子的倍数即可,比如1-10中以2为倍数的个数为102=5,那么比如N=10,N的因子有2和5,对于1-10范围内,10是2的倍数也是5的倍数,如果我们直接用102+105来计算的话,那么10的数就会被重复计算一次,那我们就要利用容斥原理来剔除重复的情况,容斥的公式如下
这里写图片描述
当是为奇数个集合条件时加,偶数个集合条件时减
也就是说比如N=10,1-100中和10不互质的数的个数为1002+100510025=60,那互质的个数就是100-60=40
所以我们先找出N的因子再利用容斥原理求出与N互质的数的个数再总数减去就行了

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>using namespace std;int a[10000],num;void init(int n){    num=0;    for(int i=2;i*i<=n;i++)    {        if(n%i==0)        {            a[num++]=i;            while(n%i==0) n/=i;        }    }    if(n>1)    {        a[num++]=n;    }}long long ex(long long m){    long long que[10000],sum=0,t=0;    que[t++]=-1;    for(int i=0;i<num;i++)    {        int k=t;        for(int j=0;j<k;j++)            que[t++]=que[j]*a[i]*-1;    }    for(int i=1;i<t;i++)        sum+=m/que[i];    return sum;}int main(){    long long a,b;    int t,cas=1;    scanf("%d",&t);    while(t--)    {        int n;        scanf("%lld%lld%d",&a,&b,&n);        printf("Case #%d: ",cas++);        init(n);        printf("%lld\n",b-ex(b)-(a-1-ex(a-1)));    }    return 0;}
原创粉丝点击