-1

I need an algorithm for the following:

  • I'm given a specified target sum n, and a specified limit m. These are both positive integers.
  • I want to find an integer partition of the target sum n that has as few summands as possible.
  • Each summand must be less than or equal to the limit m.
  • Within the above constraints, the summands should be as close together as possible; that is, I want n to be partitioned as evenly as possible.

So, for example, if the target sum is n = 80 and each summand must be at most m = 30, then I need at least three summands, and the most even partition is 26 + 27 + 27.

How would I compute that?

ruakh
  • 175,680
  • 26
  • 273
  • 307

2 Answers2

4

First, you get the size of the array with the following formula using integer division:

size = (variable + maximum - 1) / maximum

Next you fill the array with the following formulas:

extra = variable % size;
value = variable / size;
for each array value, set to value + 1 as long as there's extra; 
    value when the extra goes to zero.
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
0

Just a QnD Algorithm and Code...untested.

 double n=107;
    double max = 22;
    int d = (int) Math.ceil(n/max);
    int[] result = new int[d];
    int res=0, i=0,iter=0;
    while(res!=n){
        iter= (int) Math.ceil(n/d);
        while(iter+res>n) iter--;
        res+=iter;
        result[i] = iter;
        System.out.println("i: " + i + " iter: " + iter + " sum: " +res);
        i++;
    }
EsoMoa
  • 687
  • 1
  • 8
  • 19