mirror of
https://bitbucket.org/Mattrixwv/javaclasses.git
synced 2025-12-06 23:13:57 -05:00
Updated algorithm for efficiency
This commit is contained in:
@@ -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;
|
||||||
|
|||||||
Reference in New Issue
Block a user