Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stephen-maina/89189e79cd91ef2c74db to your computer and use it in GitHub Desktop.
Save stephen-maina/89189e79cd91ef2c74db to your computer and use it in GitHub Desktop.
not fast enough
import java.math.BigInteger;
import java.util.Random;
class Solution {
private static final Random rnd = new Random();
public static boolean miller_rabin(BigInteger n) {
for (int repeat = 0; repeat < 20; repeat++) {
BigInteger a;
do {
a = new BigInteger(n.bitLength(), rnd);
} while (a.equals(BigInteger.ZERO));
if (!miller_rabin_pass(a, n)) {
return false;
}
}
return true;
}
private static boolean miller_rabin_pass(BigInteger a, BigInteger n) {
BigInteger n_minus_one = n.subtract(BigInteger.ONE);
BigInteger d = n_minus_one;
int s = d.getLowestSetBit();
d = d.shiftRight(s);
BigInteger a_to_power = a.modPow(d, n);
if (a_to_power.equals(BigInteger.ONE)) return true;
for (int i = 0; i < s-1; i++) {
if (a_to_power.equals(n_minus_one)) return true;
a_to_power = a_to_power.multiply(a_to_power).mod(n);
}
if (a_to_power.equals(n_minus_one)) return true;
return false;
}
public int solution(int N) {
// write your code in Java SE 8
if(miller_rabin(new BigInteger(String.valueOf(N)))){
return 2*(N+1);
}
int width=0;
int minPer=Integer.MAX_VALUE;
for(int length=1;length<=N;length++){
if(N%length==0){
width=N/length;
minPer=Math.min(minPer,2*(length+width));
}
}
return minPer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment