I am trying to automate the finding of the closest factor of a number to another number;
Example:
Closest factor of 700 to 30 is 28 (30 does not go into 700, but 28 does).
An obvious solution is just to get all the factors of 700 and do a simple distance calculation to find the nearest factor to 30, but this seems to be inefficient.
Another solution is to find all the base prime factors, like:
private List<Integer> getPrimeFactors(int upTo) {
List<Integer> result = new ArrayList<>();
for (int i = 2; i <= upTo; i++) {
if (upTo % i == 0) {
result.add(i);
}
}
return result;
}
And multiplying each of these numbers together to get all the combinations, and therefore find the closest.
I am trying to programme this so it is automated. Any better solutions?
The algorithm to do this is simple; take the square root of your number as an integer (you want to truncate, not round). Test if that value is a factor of your input; if so, your input divided by that number are your answer.
So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5. We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.
Factors of 18: 1, 2, 3, 6, 9 and 18.
I have my solution wrapped in a small static method:
/**
* @param target the number you want the factor to be close to
* @param number the number you want the result to be a factor of
*/
private static int getClosestFactor(int target, int number) {
for (int i = 0; i < number; i++) {
if (number % (target + i) == 0) {
return target + i;
} else if (number % (target - i) == 0) {
return target - i;
}
}
return number;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With