您的位置:首页 > 其它

HDU 4135 Co-prime(容斥原理)

2016-05-04 15:02 351 查看


Co-prime

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

Total Submission(s): 3313 Accepted Submission(s): 1286



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
求在n在a~b之间的和n互质的个数
容斥原理模板题
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>

using namespace std;
typedef long long int LL;
const LL INF=(LL)1<<62;
#define MAX 1000000
LL prime[MAX+5];
LL sprime[MAX+5];
LL q[MAX+5];
bool check[MAX+5];
LL n,a,b,cnt;
void eular()
{
memset(check,false,sizeof(check));
int tot=0;
for(LL i=2;i<MAX+5;i++)
{
if(!check[i])
prime[tot++]=i;
for(int j=0;j<tot;j++)
{
if(i*prime[j]>MAX+5) break;
check[i*prime[j]]=true;
if(i%prime[j]==0) break;
}
}
}
void Divide(LL n)
{
cnt=0;
LL t=(LL)sqrt(1.0*n);
for(LL i=0;prime[i]<=t;i++)
{
if(n%prime[i]==0)
{
sprime[cnt++]=prime[i];
while(n%prime[i]==0)
n/=prime[i];
}
}
if(n>1)
sprime[cnt++]=n;
}
LL Ex(LL n)
{
LL sum=0,t=1;
q[0]=-1;
for(LL i=0;i<cnt;i++)
{
LL x=t;
for(LL j=0;j<x;j++)
{
q[t]=q[j]*sprime[i]*(-1);
t++;
}
}
for(LL i=1;i<t;i++)
sum+=n/q[i];
return sum;
}
int main()
{
int t;
scanf("%d",&t);
eular();
int cas=0;
while(t--)
{
scanf("%lld%lld%lld",&a,&b,&n);
Divide(n);
printf("Case #%d: %lld\n",++cas,(b-Ex(b)-(a-1-Ex(a-1))));
}
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: