Skip to content

Commit 1a230bd

Browse files
authored
Add New Prime Check (#3036)
1 parent 3ebba74 commit 1a230bd

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

src/main/java/com/thealgorithms/maths/PrimeCheck.java

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,15 @@ public static void main(String[] args) {
1010
System.out.print("Enter a number: ");
1111
int n = scanner.nextInt();
1212
if (isPrime(n)) {
13-
System.out.println(n + " is a prime number");
13+
System.out.println("algo1 verify that " + n + " is a prime number");
1414
} else {
15-
System.out.println(n + " is not a prime number");
15+
System.out.println("algo1 verify that " + n + " is not a prime number");
16+
}
17+
18+
if (fermatPrimeChecking(n, 20)) {
19+
System.out.println("algo2 verify that " + n + " is a prime number");
20+
} else {
21+
System.out.println("algo2 verify that " + n + " is not a prime number");
1622
}
1723
scanner.close();
1824
}
@@ -38,4 +44,41 @@ public static boolean isPrime(int n) {
3844
}
3945
return true;
4046
}
47+
48+
/**
49+
* *
50+
* Checks if a number is prime or not
51+
*
52+
* @param n the number
53+
* @return {@code true} if {@code n} is prime
54+
*/
55+
public static boolean fermatPrimeChecking(int n, int iteration){
56+
long a;
57+
int up = n - 2, down = 2;
58+
for(int i=0;i<iteration;i++){
59+
a = (long)Math.floor(Math.random()*(up - down + 1) + down);
60+
if(modPow(a,n-1,n) != 1){
61+
return false;
62+
}
63+
}
64+
return true;
65+
}
66+
67+
68+
/**
69+
* *
70+
* @param a basis
71+
* @param b exponent
72+
* @param c modulo
73+
* @return (a^b) mod c
74+
*/
75+
private static long modPow(long a, long b, long c){
76+
long res = 1;
77+
for (int i = 0; i < b; i++)
78+
{
79+
res *= a;
80+
res %= c;
81+
}
82+
return res % c;
83+
}
4184
}

0 commit comments

Comments
 (0)