Co-prime
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 6408 Accepted Submission(s): 2564
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.
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 <= 10
15) and (1 <=N <= 10
9).
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
题解:容斥原理
1~a当中有多少个数与n互质转换为1~a中有多少个数与n不互质。
对n进行质因数分解,假设n=30=2*3*5 则2,3,5及其他们的倍数
一定与n不互质,即s=a/2+a/3+a/5 但是这样有问题,因为有的数是其中
两个数或三个数的倍数,因此这样加会出现重复。
因此有s=a/2+a/3+a/5-a/(2*3)-a/(2*5)-a/(3*5)
但是这样还有问题,有的是他们三个的倍数,这样就被多减了一次。
因此正确答案应该是:
s=a/2+a/3+a/5-a/(2*3)-a/(2*5)-a/(3*5)+a/(2*3*5);
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll oyes(ll a,ll n)
{
ll p[102],que[102],t=0,num=0;
for(int i=2;i*i<=n;i++)//对n质因数分解
{
if(n%i==0)
{
p[num++]=i;
while(n%i==0)n=n/i;
}
}
if(n>1)p[num++]=n;//最后若n>1则加上这个质因数
que[t++]=-1;
for(int i=0;i<num;i++)//模拟上述容斥原理过程
{
int k=t;
for(int j=0;j<k;j++)
que[t++]=que[j]*p[i]*(-1);//把之前的组合都乘上p[i]
}
ll ans=0;
for(int i=1;i<t;i++)
ans+=(a/que[i]);
return ans;
}
int main()
{
int T,cas=0;scanf("%d",&T);
while(T--)
{
ll a,b,n;scanf("%lld%lld%lld",&a,&b,&n);
printf("Case #%d: %lld\n",++cas,b-a+1-oyes(b,n)+oyes(a-1,n));
}
return 0;
}