-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFig10_63.java
More file actions
58 lines (49 loc) · 1.53 KB
/
Fig10_63.java
File metadata and controls
58 lines (49 loc) · 1.53 KB
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
public class Fig10_63
{
/**
* Method that implements the basic primality test.
* If witness does not return 1, n is definitely composite.
* Do this by computing a^i (mod n) and looking for
* nontrivial square roots of 1 along the way.
*/
private static long witness( long a, long i, long n )
{
if( i == 0 )
return 1;
long x = witness( a, i / 2, n );
if( x == 0 ) // If n is recursively composite, stop
return 0;
// n is not prime if we find a nontrivial square root of 1
long y = ( x * x ) % n;
if( y == 1 && x != 1 && x != n - 1 )
return 0;
if( i % 2 != 0 )
y = ( a * y ) % n;
return y;
}
/**
* The number of witnesses queried in randomized primality test.
*/
public static final int TRIALS = 5;
/**
* Randomized primality test.
* Adjust TRIALS to increase confidence level.
* @param n the number to test.
* @return if false, n is definitely not prime.
* If true, n is probably prime.
*/
public static boolean isPrime( long n )
{
Random r = new Random( );
for( int counter = 0; counter < TRIALS; counter++ )
if( witness( r.randomLong( 2, n - 2 ), n - 1, n ) != 1 )
return false;
return true;
}
public static void main( String [ ] args )
{
for( int i = 101; i < 200; i += 2 )
if( isPrime( i ) )
System.out.println( i + " is prime" );
}
}