1
2
3
4
5
6
7
8
9
10
11
12
13class Prime {
14
15
16
17
18
19 public static
20 void main(String[] args) {
21 System.out.println
22 ( "prime number test\n"
23 + "\n"
24 + "test cases:\n"
25 + "\n"
26 + "isPrime( 1) == " + isPrime( 1) + "\n"
27 + "isPrime( 2) == " + isPrime( 2) + "\n"
28 + "isPrime( 11) == " + isPrime( 11) + "\n"
29 + "isPrime( 91) == " + isPrime( 91) + "\n"
30 + "isPrime(561) == " + isPrime(561) + "\n"
31 + "\n"
32 + "smallestDivisor( 11) == " + smallestDivisor( 11) + "\n"
33 + "smallestDivisor( 91) == " + smallestDivisor( 91) + "\n"
34 + "smallestDivisor(561) == " + smallestDivisor(561) + "\n"
35 + "\n"
36 + "isPrimeProduct( 1) == " + isPrimeProduct( 1) + "\n"
37 + "isPrimeProduct( 2) == " + isPrimeProduct( 2) + "\n"
38 + "isPrimeProduct( 11) == " + isPrimeProduct( 11) + "\n"
39 + "isPrimeProduct( 91) == " + isPrimeProduct( 91) + "\n"
40 + "isPrimeProduct(561) == " + isPrimeProduct(561) + "\n"
41 );
42
43 try {
44 isPrime(-1);
45 }
46
47 catch (IllegalArgumentException e) {
48 System.out.println
49 ( "isPrime(-1): exception: " +
50 e.getMessage());
51 }
52
53 }
54
55
56
57 protected static
58 long findDivisor(long n,
59 long i) {
60 return
61 (i * i > n)
62 ? n
63 : (n % i) == 0
64 ? i
65 : findDivisor(n, i+1);
66 }
67
68
69
70 public static
71 long smallestDivisor(long n)
72 {
73 assert n > 0;
74
75 return
76 findDivisor(n,2);
77 }
78
79
80
81 public static
82 boolean isPrime(long n)
83 {
84 assert n > 0;
85
86 return
87 n != 1
88 &&
89 smallestDivisor(n) == n;
90 }
91
92
93
94 public static
95 boolean isPrimeProduct(long n)
96 {
97 assert n > 0;
98
99 return
100 isPrime(n / smallestDivisor(n));
101 }
102}
103
104