Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 7488 Accepted Submission(s): 2961 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. 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}.Source The Third Lebanese Collegiate Programming Contest Recommend lcy | We have carefully selected several similar problems for you: 1796 1434 3460 1502 4136 |
题目大意:给出一个区间【a,b】这个区间内有多少个与p互质的数。
思路:将质因数分解,然后通过二进制枚举还有容斥原理求出与其不互质的个数,然后减去就可以了,不过要求得的【1,a】和【1,b】区间上的,最后结果相减即可。
可以观察一下:容斥原理的理解与应用
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
ll fac[maxn], sum;
void init(ll p)
{
sum = 0;
ll tmp = p;
for(ll i = 2; i*i<=tmp; i++)
if(tmp%i==0)
{
fac[sum++] = i;
while(tmp%i==0)
tmp /= i;
}
if(tmp>1)
fac[sum++] = tmp;
}
ll RC_ER(ll n)
{
if(n==1)
return 1;
ll ans=0;
for(int i=1; i<(1<<sum); i++)
{
ll p=1,cnt=0;
for(int j=0; j<sum; j++)
if(i&(1<<j))
{
p*=fac[j];
cnt++;
}
if(cnt%2==0)
{
ans-=n/p;
}
else
{
ans+=n/p;
}
}
return n-ans;
}
int main()
{
int t;
int k=0;
scanf("%d",&T);
while(t--)
{
memset(fac,0,sizeof(fac));
k++;
ll a,b,p;
scanf("%lld%lld%lld",&a,&b,&p);
init(p);
printf("Case #%d: %lld\n",k,RC_ER(b)-RC_ER(a-1));
}
return 0;
}