Co-prime
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2371 Accepted Submission(s): 887
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 <= 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}. 容斥原理...注意重叠部分
n小的时候可以用欧拉函数去做。对于n比较大的 得用容斥去做
/* *********************************************** Author :PK28 Created Time :2015/8/18 9:29:57 File Name :4.cpp ************************************************ */ #include <iostream> #include <cstring> #include <cstdlib> #include <stdio.h> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <iomanip> #include <list> #include <deque> #include <stack> #define ull unsigned long long #define ll long long #define mod 90001 #define INF 0x3f3f3f3f #define maxn 10000+10 #define cle(a) memset(a,0,sizeof(a)) const ull inf = 1LL << 61; const double eps=1e-5; using namespace std; bool cmp(int a,int b){ return a>b; } ll a,b,n; ll solve(){ ll sum=0; vector<ll>v; for(int i=2;i*i<=n;i++) if(n%i==0){ v.push_back(i); while(n%i==0)n/=i; //对n进行素数分解 } if(n>1)v.push_back(n); for(ll st=1;st<(1<<(v.size()));++st){//0 1 ll bits=0,mult=1; for(int i=0;i<(int)v.size();++i){ if(st&(1<<i)){ ++bits; //记录有几个素数被用到 mult*=v[i]; } } ll cur=b/mult-a/mult; //a b区间 不与n互质的数的个数 if(a%mult==0)cur++; if(bits&1)sum+=cur; //奇+ 偶- else sum-=cur; } return b-a-sum+1; } int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif //freopen("out.txt","w",stdout); int t; cin>>t; for(int i=1;i<=t;i++){ scanf("%I64d %I64d %I64d",&a,&b,&n); printf("Case #%d: %I64d ",i,solve()); } return 0; }
先对n分解质因数,分别记录每个质因数, 那么所求区间内与某个质因数不互质的个数就是n / r(i),假设r(i)是r的某个质因子 假设只有三个质因子,那么p1=n/r(1)
p2=n/r(2) p1和p2 有交集可以用容斥解决,那么
总的不互质的个数应该为p1+p2+p3-p1*p2-p1*p3-p2*p3+p1*p2*p3, pi代表n/r(i),即与某个质因子不互质的数的个数 ,当有更多个质因子的时候, 可以用状态压缩解决,二进制位上是1表示这个质因子被取进去了。 如果有奇数个1,就相加,反之则相减