Three-Way Minimum Sum Partitions
November 22, 2019
I had a lot of fun working on this problem:
Given n, find x, y and z such that x y z = n and x + y + z is minimal; for instance, given n = 1890, the correct answer is (9 14 15).
Your task is to write a program to find x, y and z. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
The method below is much faster than brute force. First determine all divisors and sort them in decreaing order. Loop for x starting from the cubic root downwards. Divide n by x, determine the sqrt of the result and check if it possible to improve the sum. Break if not possible. Otherwise loop downwards from this sqrt and find the first possible solution.
I will post full code later on ideone.
Full code with some changes is on Ideone.
@Paul: nice – I was thinking on similar lines, but didn’t think of the cutoff on line 10. I think that break on line 22 can be outdented (any smaller divisor than y will have a larger sum). It would be nice to do a binary search through the divisors to find the start points of the iterations.
@matthew. I saw also that I could outdent that line (see my Ideone post)
@Paul: So I see, good stuff. I’m wondering if we can remove cubic factors from n before finding the minimum sum, ie. if a+b+c = n is minimal, then is it the case that ka+kb+kc = k^3n is minimal?
@matthew. An interesting idea, but unfortunately there is a counterexample. Take 24=83. The best solution is x,y,z = 2, 3, 4 with sum 9. If you solve for n=3 with solution 1,1,3 (sum 5) the total sum is 25=10.
@matthew. Formatting caught me here, Of course, I meant 24=8×3 and 2×5=10.
@Paul: nice counterexample. Probably wouldn’t have helped much in the general case anyway.
Here’s a recursive solution in Python that supports an arbitrary number of factors, as opposed to 3 specified in the problem.
Output:
Here’s the recursive solution I posted above, with @Paul’s short-circuiting optimization. It runs noticeably faster now :-), even with the naive integer root function I wrote.
Output:
Klong solution
In addition to the brute force approach, I tried the following 2 alternatives:
1) Iterated the first loop from 1 to the floored cube root of the initial number; and
2) Iterated the first loop from 1 to the floored cube root of the initial number and iterated the 2nd loop from 1 to the floored square root of the quotient of the initial number and the 1st iterator.
The run shows one of the combinations which yields one of the least sums as well as the number of combinations before finding the minimum.
Results from the Klong run:
[Brute force: Answer – [ 9 14 15 ], # Entries – 270]
[Square root: Answer – [ 9 15 14 ], # Entries – 140]
[Cube/Square roots: Answer – [ 9 14 15 ], # Entries – 70]