Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 880
Cobbles Avatar asked Nov 12 '14 10:11

Cobbles


People also ask

How do you find two nearest factors of a number?

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.

How do I find the closest number in C++?

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.

Which set of numbers are factors of 18?

Factors of 18: 1, 2, 3, 6, 9 and 18.


1 Answers

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;
}
like image 113
Cobbles Avatar answered Oct 22 '22 01:10

Cobbles