hdu 4135 Co-prime 容斥原理

hdu 4135

具有教科书性质的容斥原理应用实例。
能不重复、不遗漏地选出所有合数,也就能得到质数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/** Aug 26, 2015 9:40:09 PM
* PrjName:hdu4135
* @author Semprathlon
*/
import java.io.*;
import java.util.*;
public class Main {
static int maxn=1001;
static int[] pri,fstp;
static Vector<Integer> vec=new Vector<Integer>();
static void get_prime(){
pri=new int[maxn];
fstp=new int[maxn];
for(int i=2;i<maxn;i++){
if (fstp[i]==0){
pri[++pri[0]]=i;
}
for(int j=1;j<=pri[0]&&i*pri[j]<maxn;j++){
int k=i*pri[j];
fstp[k]=pri[j];
if (i%pri[j]==0)
break;
}
}
}
static Vector<Integer> get_prime_factor(int n){
Vector<Integer> res=new Vector<Integer>();
res.clear();
for(int i=1;i<=pri[0]&&pri[i]*pri[i]<=n;i++)
if (n%pri[i]==0){
res.add(pri[i]);
while(n%pri[i]==0)
n/=pri[i];
}
if (n>1) res.add(n);
return res;
}
static long solve(long n,Vector<Integer> vec){
long res=0L;
final int m=vec.size();
for(long i=1L;i<(1L<<m);i++){
boolean tag=false;
long tmp=1L;
for(int j=0;j<m;j++)
if (((1L<<j)&i)>0){
tag^=true;
tmp*=vec.get(j).longValue();
}
res+=tag?n/tmp:-n/tmp;
}
return n-res;
}
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
get_prime();
InputReader in=new InputReader(System.in);
PrintWriter out=new PrintWriter(System.out);
int T=in.nextInt(),cas=0;
while(T-->0){
long a=in.nextLong();
long b=in.nextLong();
int n=in.nextInt();
vec=get_prime_factor(n);
out.println("Case #"+(++cas)+": "+(solve(b,vec)-solve(a-1,vec)));
}
out.flush();
out.close();
}
}
Author

Semprathlon / Simfae Dean

Posted on

08/26/2015

Updated on

07/19/2023

Licensed under

Comments