- Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathMiller-prime-test.java
69 lines (65 loc) · 1.99 KB
/
Miller-prime-test.java
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
/* Miller-Rabin primality test, iteration signifies the accuracy of the test */
// test number if p is prime or not using 'iterations'.
booleanMiller(longp,intiteration){
longLOWER_RANGE = 1; //assign lower range value
longUPPER_RANGE = p-1; //assign upper range value
RandomrandomGenerator = newRandom();
if(p<2){
returnfalse;
}
if(p!=2 && p%2==0){
returnfalse;
}
longs=p-1;
while(s%2==0){
s/=2;
}
for(inti=0;i<iteration;i++){
longrandomValue = LOWER_RANGE + (long)(randomGenerator.nextDouble()*(UPPER_RANGE - LOWER_RANGE));
longa = randomValue %(p-1)+1,temp=s;
longmod= pow(a,temp,p);
while(temp!=p-1 && mod!=1 && mod!=p-1){
mod = pow(mod,mod,p);
temp *= 2;
}
if(mod!=p-1 && temp%2==0){
returnfalse;
}
}
returntrue;
}
// sieve
// Better Optioin : BigInteger is Probable prime
importjava.io.*;
importjava.util.*;
importjava.text.*;
importjava.math.*;
importjava.util.regex.*;
publicclassSolution {
staticlongnext(longx) {
if (x == 0) {
return0;
}
longy = x / 10;
longy1 = next(y + (x % 10 > 7 ? 1 : 0));
if (y != y1) {
return10 * y1 + 2;
}
returny1 * 10 + (x % 10 <= 2 ? 2 : x % 10 <= 3 ? 3 : x % 10 <= 5 ? 5 : 7);
}
publicstaticvoidmain(String[] args) {
Scannerin = newScanner(System.in);
longfirst = in.nextLong();
longlast = in.nextLong();
longans = 0;
first = next(first);
while (first <= last) {
//System.err.println(first);
if (BigInteger.valueOf(first).isProbablePrime(20)) { // 20 is rounds
ans++;
}
first = next(first + 1);
}
System.out.println(ans);
}
}