The code below is for testing Primes.
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 < n) {
long s = 0;
long d = n - 1;
while (d % 2 == 0) {
s++;
d /= 2;
}
long x = modpow(a, d, n);
if (x != 1 && x != n - 1) {
for (long r = 1; r < s; r++) {
x = (x * x) % n;
if (x == 1) {
return false;
}
if (x == n - 1) {
continue outer;
}
}
return false;
}
}
}
return true;
}
public static boolean IsPrime(long num) {
if (num <= 1) {
return false;
} else if (num <= 3) {
return true;
} else if (num % 2 == 0) {
return false;
} else {
return millerRabin(num);
}
}
public static int[] primes(int min, int max) {
ArrayList<Integer> primesList = new ArrayList<Integer>();
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 class
if (a < n) { continue;}
is better no jump to end of if statement before going to loop, but it would depends on compiler clerverness \$\endgroup\$ – cl-r Sep 24 '13 at 6:28c % 2 == 1
in Java guaranteed to optimize down to the same asc & 1 == 0
? The reason I ask is because the type ofc
islong
, which is signed, so this might force the JVM to use an actual divide-by-2-and-get-remainder operation rather than simply a boolean 'and' operation to extract the least-significant bit. If so, the speed difference is likely to be very minimal, but it still might be worth profiling things to check. Also,c /= 2
could be written asc >>>= 1
. \$\endgroup\$ – Todd Lehman Jul 29 '14 at 3:42{ 2, 7, 61 }
comes from, and what the limitations are on your input. \$\endgroup\$ – Todd Lehman Jul 29 '14 at 3:56