Skip to content
Advertisement

Find closest factor to a number, of a number

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?

Answer

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;
}
Advertisement