Skip to content

Commit 0f7a2fb

Browse files
authored
Java implementation of Miller-Rabin Primality Test
1 parent a8a6550 commit 0f7a2fb

File tree

1 file changed

+107
-0
lines changed
  • Math/miller_rabin_primality_test

1 file changed

+107
-0
lines changed

Diff for: Math/miller_rabin_primality_test/mrp.java

+107
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// Java program Miller-Rabin primality test
2+
import java.io.*;
3+
import java.math.*;
4+
5+
class GFG {
6+
7+
// Utility function to do modular
8+
// exponentiation. It returns (x^y) % p
9+
static int power(int x, int y, int p) {
10+
11+
int res = 1; // Initialize result
12+
13+
//Update x if it is more than or
14+
// equal to p
15+
x = x % p;
16+
17+
while (y > 0) {
18+
19+
// If y is odd, multiply x with result
20+
if ((y & 1) == 1)
21+
res = (res * x) % p;
22+
23+
// y must be even now
24+
y = y >> 1; // y = y/2
25+
x = (x * x) % p;
26+
}
27+
28+
return res;
29+
}
30+
31+
// This function is called for all k trials.
32+
// It returns false if n is composite and
33+
// returns false if n is probably prime.
34+
// d is an odd number such that d*2<sup>r</sup>
35+
// = n-1 for some r >= 1
36+
static boolean miillerTest(int d, int n) {
37+
38+
// Pick a random number in [2..n-2]
39+
// Corner cases make sure that n > 4
40+
int a = 2 + (int)(Math.random() % (n - 4));
41+
42+
// Compute a^d % n
43+
int x = power(a, d, n);
44+
45+
if (x == 1 || x == n - 1)
46+
return true;
47+
48+
// Keep squaring x while one of the
49+
// following doesn't happen
50+
// (i) d does not reach n-1
51+
// (ii) (x^2) % n is not 1
52+
// (iii) (x^2) % n is not n-1
53+
while (d != n - 1) {
54+
x = (x * x) % n;
55+
d *= 2;
56+
57+
if (x == 1)
58+
return false;
59+
if (x == n - 1)
60+
return true;
61+
}
62+
63+
// Return composite
64+
return false;
65+
}
66+
67+
// It returns false if n is composite
68+
// and returns true if n is probably
69+
// prime. k is an input parameter that
70+
// determines accuracy level. Higher
71+
// value of k indicates more accuracy.
72+
static boolean isPrime(int n, int k) {
73+
74+
// Corner cases
75+
if (n <= 1 || n == 4)
76+
return false;
77+
if (n <= 3)
78+
return true;
79+
80+
// Find r such that n = 2^d * r + 1
81+
// for some r >= 1
82+
int d = n - 1;
83+
84+
while (d % 2 == 0)
85+
d /= 2;
86+
87+
// Iterate given nber of 'k' times
88+
for (int i = 0; i < k; i++)
89+
if (!miillerTest(d, n))
90+
return false;
91+
92+
return true;
93+
}
94+
95+
// Driver program
96+
public static void main(String args[]) {
97+
98+
int k = 4; // Number of iterations
99+
100+
System.out.println("All primes smaller "
101+
+ "than 100: ");
102+
103+
for (int n = 1; n < 100; n++)
104+
if (isPrime(n, k))
105+
System.out.print(n + " ");
106+
}
107+
}

0 commit comments

Comments
 (0)