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 <= 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
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互素的数;
很显然a~b与n互素的个数=1~b与n互素的个数-1~(a-1)与n互素的个数;
因为a,b,n的数值很大,所以我们可以用容斥原理先求出1~(a-1)与n互素的个数,a-1-互素的个数就时不互素的个数;
求不互素的方法:先分解出n的素因子,假设n=30,a=100,那么他的素因子就有2,3,5,那么1~100中与30不互素的就有是2,3,5倍数的-即是2又是3倍数的-即是2又是5倍数的-即是3又是5倍数的<3,5是两个数即为偶数>+即是2又是3又是5倍数的。(总结起来就是奇正偶负);
代码如下:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
#include<map>
#include<stack>
#include<vector>
#include<cstdlib>
#include<ctime>
#define mem(a,b) memset(a,b,sizeof(a))
#define ll long long
using namespace std;
const int MAXN=100000+10;
const int inf=0x3f3f3f;
ll tot;
ll a[MAXN];
void init(ll m)//分解素因子
{
mem(a,0);
tot=0;
for(ll i=2;i*i<=m;i++)
{
if(m%i==0)
{
a[tot++]=i;
while(m%i==0)
m/=i;
}
}
if(m>1) a[tot++]=m;
}
ll Repulsion(ll m)//容斥原理
{
ll que[10000];
ll sum=0,t=0,k;
que[t++]=-1;
for(ll i=0;i<tot;i++)
{
k=t;
for(int j=0;j<k;j++)
que[t++]=que[j]*a[i]*(-1);
}
for(ll i=1;i<t;i++)
sum+=(m/que[i]);
return sum;
}
int main()
{
int T,t=0;
scanf("%d",&T);
ll a1,b1,c;
while(T--)
{
scanf("%lld %lld %lld",&a1,&b1,&c);
init(c);
ll sum1=a1-1-Repulsion(a1-1);
ll sum2=b1-Repulsion(b1);
printf("Case #%d: %lld\n",++t,sum2-sum1);
}
}