forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMillerRabinTest.java
More file actions
63 lines (60 loc) · 1.4 KB
/
MillerRabinTest.java
File metadata and controls
63 lines (60 loc) · 1.4 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
59
60
61
62
63
import java.util.Scanner;
import java.lang.Math;
class MillerRabinTest
{
public static int power(int a,int n, int p)
{
int res = 1;
a = a % p;
while (n > 0)
{
if ((n & 1) == 1)
res = (res * a) % p;
n = n >> 1;
a = (a * a) % p;
}
return res;
}
public static boolean millerTest(int d, int n)
{
int a = 2 + (int)(Math.random() % (n - 4));
int x = power(a, d, n);
if (x == 1 || x == n - 1)
return true;
while (d != n - 1)
{
x = (x * x) % n;
d *= 2;
if (x == 1)
return false;
if (x == n - 1)
return true;
}
return false;
}
static boolean isPrime(int n, int k)
{
if (n <= 1 || n == 4)
return false;
if (n <= 3)
return true;
int d = n - 1;
while (d % 2 == 0)
d /= 2;
for (int i = 0; i < k; i++)
if (!millerTest(d, n))
return false;
return true;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int num;
num = sc.nextInt();
if(isPrime(num, 50))
System.out.println("Number is Prime");
else
System.out.println("Number is not Prime");
}
}