Created isPrime function

This commit is contained in:
2020-10-30 16:27:26 -04:00
parent fcbcb1f806
commit 2cbe4b4389

View File

@@ -306,6 +306,51 @@ public class Algorithms{
Collections.sort(primes);
return primes;
}
//This function return true if the value passed to it is prime
public static boolean isPrime(int possiblePrime){
if(possiblePrime <= 3){
return possiblePrime > 1;
}
else if(((possiblePrime % 2) == 0) || ((possiblePrime % 3) == 0)){
return false;
}
for(int cnt = 5;(cnt * cnt) <= possiblePrime;cnt += 6){
if(((possiblePrime % cnt) == 0) || ((possiblePrime % (cnt + 2)) == 0)){
return false;
}
}
return true;
}
//This function return true if the value passed to it is prime
public static boolean isPrime(long possiblePrime){
if(possiblePrime <= 3){
return possiblePrime > 1;
}
else if(((possiblePrime % 2) == 0) || ((possiblePrime % 3) == 0)){
return false;
}
for(long cnt = 5;(cnt * cnt) <= possiblePrime;cnt += 6){
if(((possiblePrime % cnt) == 0) || ((possiblePrime % (cnt + 2)) == 0)){
return false;
}
}
return true;
}
//This function return true if the value passed to it is prime
public static boolean isPrime(BigInteger possiblePrime){
if(possiblePrime.compareTo(BigInteger.valueOf(3)) <= 0){
return possiblePrime.compareTo(BigInteger.ONE) > 0;
}
else if(possiblePrime.mod(BigInteger.TWO).equals(BigInteger.ZERO) || possiblePrime.mod(BigInteger.valueOf(3)).equals(BigInteger.ZERO)){
return false;
}
for(BigInteger cnt = BigInteger.valueOf(5);(cnt.multiply(cnt)).compareTo(possiblePrime) <= 0;cnt = cnt.add(BigInteger.valueOf(6))){
if(possiblePrime.mod(cnt).equals(BigInteger.ZERO) || possiblePrime.mod(cnt.add(BigInteger.TWO)).equals(BigInteger.ZERO)){
return false;
}
}
return true;
}
//This function returns all factors of goalNumber
public static ArrayList<Integer> getFactors(Integer goalNumber) throws InvalidResult{
//You need to get all the primes that could be factors of this number so you can test them