#C12246. Generate Natural Numbers with a Target Sum
Generate Natural Numbers with a Target Sum
Generate Natural Numbers with a Target Sum
You are given two integers, n
and target
. Your task is to generate a list of n natural numbers (i.e. positive integers) whose sum is exactly equal to target
. If such a list does not exist, output an empty list.
The minimal possible sum for n natural numbers is given by the formula:
\( S_{min} = 1 + 2 + \cdots + n = \frac{n(n+1)}{2} \)
If \( target < S_{min} \) or if n ≤ 0
, then no valid list exists and you should output an empty list ([]
).
To construct a valid list when \( target \geq S_{min} \), start with the list \([1, 2, \dots, n]\) and distribute the extra amount \( target - S_{min} \) by incrementing the numbers (starting from the end of the list and cycling backwards) until the total sum equals target
. This guarantees that you output exactly n natural numbers that sum to target
.
inputFormat
The input is read from stdin and consists of a single line containing two integers n
and target
separated by whitespace.
outputFormat
Output the n natural numbers separated by a single space if a valid list exists. If no valid list is possible, output []
. The output should be written to stdout.
3 6
1 2 3