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\frac{10}{2}=5210=5,那么比如N=10,N的因子有2和5,对于1-10范围内,10是2的倍数也是5的倍数,如果我们直接用102+105\frac{10}{2}+\frac{10}{5}210+510来计算的话,那么10的数就会被重复计算一次,那我们就要利用容斥原理来剔除重复的情况,容斥的公式如下
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QR7oCvtq-1601531427181)(https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/s=592/sign=3ef1ffbf1fd8bc3ec20806c3b08aa6c8/0ff41bd5ad6eddc403aafe7e3fdbb6fd536633e1.jpg)]
当是为奇数个集合条件时加,偶数个集合条件时减
也就是说比如N=10,1-100中和10不互质的数的个数为1002+1005−1002∗5=60\frac{100}{2}+\frac{100}{5}-\frac{100}{2*5}=602100+5100−2∗5100=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;
}