OK, all you math types....
Aug. 14th, 2008 03:42 pmHere's a math problem I've been struggling with. Well, I've been struggling with its practical application, and I'm going to write an Excel spreadsheet to solve it by brute force, but I wonder if it would fall to an elegant algorithm.
Given a number N and two smaller numbers a and b, find x such that x ∊ [a, b] and N mod x is maximized.
(Practical application: Given 2,711 squares, each color-coded to indicate the status of one member of a sequence, arrange them in a rectangle whose width is between 70 and 90 such that there are the fewest number of unused squares in the lower right-corner. Excel tells me that the answer is width 80, which has 9 leftover squares.)
Given a number N and two smaller numbers a and b, find x such that x ∊ [a, b] and N mod x is maximized.
(Practical application: Given 2,711 squares, each color-coded to indicate the status of one member of a sequence, arrange them in a rectangle whose width is between 70 and 90 such that there are the fewest number of unused squares in the lower right-corner. Excel tells me that the answer is width 80, which has 9 leftover squares.)
from the cs point of view
Date: 2008-08-14 08:11 pm (UTC)Are you trying to maximize N mod x or x - N mod x? 85 is a better answer for the first and equivalent for the second.
(no subject)
Date: 2008-08-14 08:17 pm (UTC)Factor N. If any of its factors (not just prime factors) is in [a,b], x is that factor and the number of unused squares is 0. Otherwise, factor N+1, etc. until you find a factor in the range - that factor is your x and the addition is the number of unused squares. For your case, 2720's prime factors are 2^5, 5, and 17 - 80 is 2^4 * 5 and 85 is 5*17.
Re: from the cs point of view
Date: 2008-08-14 08:17 pm (UTC)Re: from the cs point of view
Date: 2008-08-14 08:23 pm (UTC)I know that in general mod is not reversable, but sometimes for specific problems there are good approximations.
Or there might be an approach that takes N mod 2, N mod 3, and N mod 5 and uses that to reduce or at least prioritize the search space.
Re: from the cs point of view
Date: 2008-08-14 08:27 pm (UTC)Re: from the cs point of view
Date: 2008-08-14 08:36 pm (UTC)(no subject)
Date: 2008-08-14 09:20 pm (UTC)I guess, looking at it a different way, you could try floor(N/b) through ceil(N/a) as possible quotients, work back to compute the subrange of [a,b] that would produce each quotient, and the smallest number in each subrange would produce the largest remainder. I don't know if that helps or hurts; I think if a>sqrt(N) the new range is probably smaller than [a,b].
Re: from the cs point of view
Date: 2008-08-14 09:52 pm (UTC)(no subject)
Date: 2008-08-15 05:06 am (UTC)p = N % b;
q = N / b; (integer division rounding down)
for (c=b-1; c >=a; c--)
{
pnew = ((q + p) % c);
if (pnew < p) q++;
p = pnew;
}
By the way, 85 rows also yields a last row with only 9 unfilled entries.
(no subject)
Date: 2008-08-15 05:11 am (UTC)