Given an integer N I want to find two integers A and B that satisfy A × B ≥ N with the following conditions:
- The difference between A × B and N is as low as possible.
- The difference between A and B is as low as possible (to approach a square).
Example: 23. Possible solutions 3 × 8, 6 × 4, 5 × 5. 6 × 4 is the best since it leaves just one empty space in the grid and is “less” rectangular than 3 × 8.
Another example: 21. Solutions 3 × 7 and 4 × 6. 3 × 7 is the desired one.
A brute force solution is easy. I would like to see if a clever solution is possible.
Easy.
In pseudocode
and it will always terminate, the distance between
aandbat most only 1.It will be much harder if you relax second constraint, but that’s another question.
Edit: as it seems that the first condition is more important, you have to attack the problem
a bit differently. You have to specify some method to measure the badness of not being square enough = 2nd condition, because even prime numbers can be factorized as
1*number, and we fulfill the first condition. Assume we have a badness function (saya >= b && a <= 2 * b), then factorizeNand try different combinations to find best one. If there aren’t any good enough, try withN+1and so on.Edit2: after thinking a bit more I come with this solution, in Python:
which outputs