Updated algorithm for efficiency

This commit is contained in:
2022-12-04 21:48:38 -05:00
parent 77b510f69e
commit 783fc7009c

View File

@@ -238,7 +238,7 @@ public class NumberAlgorithms{
}
public static List<Long> getFactors(long goalNumber) throws InvalidResult{
//You need to get all the primes that could be factors of this number so you can test them
Double topPossiblePrime = Math.ceil(goalNumber / 2.0);
Double topPossiblePrime = Math.ceil(Math.sqrt(goalNumber));
List<Long> primes = getPrimes(topPossiblePrime.longValue());
ArrayList<Long> factors = new ArrayList<>();
@@ -264,7 +264,12 @@ public class NumberAlgorithms{
//If for some reason the goalNumber is not 1 throw an error
if(goalNumber != 1){
throw new InvalidResult("The factor was not 1: " + goalNumber);
if(isPrime(goalNumber)){
factors.add(goalNumber);
}
else{
throw new InvalidResult("The factor was not 1: " + goalNumber);
}
}
//Return the list of factors