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{ 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 //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()); List<Long> primes = getPrimes(topPossiblePrime.longValue());
ArrayList<Long> factors = new ArrayList<>(); ArrayList<Long> factors = new ArrayList<>();
@@ -264,8 +264,13 @@ public class NumberAlgorithms{
//If for some reason the goalNumber is not 1 throw an error //If for some reason the goalNumber is not 1 throw an error
if(goalNumber != 1){ if(goalNumber != 1){
if(isPrime(goalNumber)){
factors.add(goalNumber);
}
else{
throw new InvalidResult("The factor was not 1: " + goalNumber); throw new InvalidResult("The factor was not 1: " + goalNumber);
} }
}
//Return the list of factors //Return the list of factors
return factors; return factors;