您的位置:首页 > 其它

HDOJ 4135 Co-prime (容斥原理)

2015-11-11 20:14 274 查看

Co-prime

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 2751    Accepted Submission(s): 1055


[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
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).
 

[align=left]Output[/align]
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.
 

[align=left]Sample Input[/align]

2
1 10 2
3 15 5

 

[align=left]Sample Output[/align]
Case #1: 5
Case #2: 10

HintIn 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互质的数的个数

思路:这个题一看就会想到欧拉函数,但是稍微一想就会发现,eular(A)-eular(B)是不可行的,因为会有重复项出现,所以就想到了容斥原理
先求出1-A中与N不互斥的数,然后用A减一下就得到了和N互斥的数的个数。例如:A=12,N =30,
那么:求出N的质因子为:2,3,5,
容斥原理公式:ans=N/2+N/3+N/5-N/(2*3)-N/(2*5)-N/(3*5)+N/(2*3*5)。
用队列数组法实现容斥原理:
que数组保存分母的大小,开始时数组没有数,然后给其赋值,k为质因子的数目,所以最高的que也就是k个质因子相乘,在遍历第i个质因子的时候
对之前的que数组进行累乘,例如:que[1]=2,que[2]=3,que[3]=2*3,que[4]=5,que[5]=2*5,que[6]=3*5,que[7]=2*3*5, 在这个过程中对其进行变号确定其正
负,最后遍历用num相处然后累加就行了。

ac代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#define fab(a) (a)>0?(a):(-a)
#define LL long long
#define MAXN 10010
#define INF 0xfffffff
using namespace std;
LL aprime[MAXN];
LL k;
void findprime(LL x)//求一个数的质因子
{
k=0;
for(LL i=2;i*i<=x;i++)
{
if(x%i==0)
{
aprime[k++]=i;
while(x%i==0)
x/=i;
}
}
if(x>1)//不可少
aprime[k++]=x;
}
LL fun(LL num)//队列法实现容斥原理
{
LL que[MAXN],i,j,kk,ans=0,t=0;
que[t++]=-1;
for(i=0;i<k;i++)
{
kk=t;
for(j=0;j<kk;j++)
que[t++]=aprime[i]*que[j]*(-1);
}
for(i=1;i<t;i++)
ans+=(num/que[i]);
return ans;
}
int main()
{
int t;
int cas=0;
LL a,b,n;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld%lld",&a,&b,&n);
findprime(n);
LL ans=(b-fun(b))-(a-1-fun(a-1));
printf("Case #%d: %lld\n",++cas,ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: