patternjavaMinor
Miller-Rabin Prime test (Speed is the main goal)
Viewed 0 times
thegoalrabinmaintestprimespeedmiller
Problem
The code below is for testing Primes.
Now my goal is to make the code super fast at finding prime number, min-max, close prime.
Are there any improvements that can be done to the code below to improve the speed for
testPrime(100000);
testPrime(1000000);
testPrime(10000000);
testPrime(100000000);Now my goal is to make the code super fast at finding prime number, min-max, close prime.
Are there any improvements that can be done to the code below to improve the speed for
IsPrime?import java.util.ArrayList;
import java.math.*;
class Primes {
private static long[] as = {2, 7, 61};
private static long modpow(long x, long c, long m) {
long result = 1;
long aktpot = x;
while (c > 0) {
if (c % 2 == 1) {
result = (result * aktpot) % m;
}
aktpot = (aktpot * aktpot) % m;
c /= 2;
}
return result;
}
private static boolean millerRabin(long n) {
outer:
for (long a : as) {
if (a primesList = new ArrayList();
for( int i=min; i<max; i++ ){
if( IsPrime(i) ){
primesList.add(i);
}
}
int[] primesArray = new int[primesList.size()];
for(int i=0; i<primesArray.length; i++){
primesArray[i] = (int) primesList.get(i);
}
return primesArray;
}
public static String tostring (int [] arr){
String ans="";
for (int i=0; i<arr.length;i++){
ans= ans+arr[i]+ " ";
}
return ans;
}
public static int closestPrime(int num) {
int count=1;
for (int i=num;;i++){
int plus=num+count, minus=num-count;
if (IsPrime(minus)){
return minus;
}
if (IsPrime(plus)) {
return plus;
}
count=count+1;
}
}
}
//end classSolution
You could use the Sieve of Eratosthenes for numbers less than 10 million (you are only going up to 100 million).
I think that checking the low bit
You might experiment with doing an initial check for division by a few low primes (3, 5, 7, 11) in your IsPrime method and see if that makes a difference.
Finally, for your "random" numbers, you might want to choose products of primes, e.g. 3571113..., or maybe that plus 1. Maybe that's crazy. But some "random" numbers might provide richer test cases than others, and cause a faster elimination of non-primes.
I think that checking the low bit
(num & 1) == 0 is quicker than checking the remainder num % 2 == 0. Similarly, bit shifting is quicker for division or multiplication by 2: d /= 2 could be d >> 1.You might experiment with doing an initial check for division by a few low primes (3, 5, 7, 11) in your IsPrime method and see if that makes a difference.
Finally, for your "random" numbers, you might want to choose products of primes, e.g. 3571113..., or maybe that plus 1. Maybe that's crazy. But some "random" numbers might provide richer test cases than others, and cause a faster elimination of non-primes.
Context
StackExchange Code Review Q#24625, answer score: 4
Revisions (0)
No revisions yet.