Algorithm to get x amount of numbers that add up to a certain number. With most of the numbers being common. e.g. Input: 8, x = 3 Output: 3,3,2

algorithms

Want to know if there is an algorithm to get x amount of numbers that add up to a certain number. With most of the numbers being common. e.g. Input: 8, x = 3 Output: 3,3,2

Output should not be 2,2,4. The output numbers should be as close as possible.

Input: 10, x = 4 Output: 3,3,3,1

To clarify, the range of the numbers that add to the sum must be minimal.

Each number must be greater than 0.

My current attempt.

y = target, x = amount of numbers to reach y

y/x = z Round down z to the nearest integer.

a = y – (z*x-1)
output: z repeated x-1 times + a

10/3 = 3

4 = 10 – (3*2)

output: 3,3,4

Thank you

Best Answer

Your algorithm is ALMOST correct. "Round down z to the nearest integer"- instead of this, just round z to the highest integer(and obviously it'll remain the same if z is integer). For eg, if z=1.4 or 1.6, z will become 2.

Related Question