hdu_4135_Co-prime

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.

InputThe 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 <= 10 15) and (1 <=N <= 10 9).OutputFor 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}. 
        
 
首先分解质因子,然后利用容斥原理分别求出0—(A-1 )的不互质个数和0—(B)的不互质个数,答案可求。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define LL long long
#define maxn 70

LL p[maxn];
LL make_ans(LL num,int m)//1到num中的所有数与m个质因子不互质的个数 注意是不互质哦
{
	LL ans=0,tmp,i,j,flag;
	for(i=1;i<(LL)(1<<m);i++)
	{ //用二进制来1,0来表示第几个素因子是否被用到,如m=3,三个因子是2,3,5,则i=3时二进制是011,表示第2、3个因子被用到
		tmp=1,flag=0;
		for(j=0;j<m;j++)
			if(i&((LL)(1<<j)))//判断第几个因子目前被用到
				flag++,tmp*=p[j];
		if(flag&1)//容斥原理,奇加偶减
			ans+=num/tmp;
		else
			ans-=num/tmp;
	}
	return ans;
}

int main()
{
	int T,t=0,m;
	LL n,a,b,i;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%lld%lld%lld",&a,&b,&n);
		m=0;
		for(i=2;i*i<=n;i++) //对n进行素因子分解
			if(n&&n%i==0)
			{
				p[m++]=i;
				while(n%i==0)
					n/=i;
			}
		if(n!=1)
			p[m++]=n;
		printf("Case #%d: %I64d\n",++t,(b-make_ans(b,m))-(a-1-make_ans(a-1,m)));
	}
	return 0;
}

  

posted @ 2017-12-19 15:19  会飞的雅蠛蝶  阅读(133)  评论(0编辑  收藏  举报