File tree Expand file tree Collapse file tree 1 file changed +45
-2
lines changed
src/main/java/com/thealgorithms/maths Expand file tree Collapse file tree 1 file changed +45
-2
lines changed Original file line number Diff line number Diff line change @@ -10,9 +10,15 @@ public static void main(String[] args) {
10
10
System .out .print ("Enter a number: " );
11
11
int n = scanner .nextInt ();
12
12
if (isPrime (n )) {
13
- System .out .println (n + " is a prime number" );
13
+ System .out .println ("algo1 verify that " + n + " is a prime number" );
14
14
} 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" );
16
22
}
17
23
scanner .close ();
18
24
}
@@ -38,4 +44,41 @@ public static boolean isPrime(int n) {
38
44
}
39
45
return true ;
40
46
}
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
+ }
41
84
}
You can’t perform that action at this time.
0 commit comments