It is easy to create a single number within the range [0, 255] .
It is easy to identify if k > 255*n or k < 0 there is no solution.
If 0 <= k <= 255*n , a solution exists. Here we are only talking about the state n > 1 .
You created n-1 random numbers, and the sum of the numbers n-1 is s1 , suppose the nth number is x . So, s1 + x = k , and x should be [0, 255] . If the numbers n-1 are within the range [0, a] , then (n-1)*a + 255 >= k , we get a >= (k-255)/(n-1) .
If k > 255 , just let a = (k-255)/(n-1) . This means that s1 is [0, k-255] . Then the nth number x can be any random number inside [0, 255] . Thus, the solution arbitrarily selects n-1 numbers within [0, (k-255)/(n-1)] (you know (k-255)/(n-1) <= 255 , so it satisfies your condition) and choose one random number within [0, 255] .
If k <= 255 , an arbitrary choice of n numbers within [0, k/n] (you know that k/n is within [0, 255]).
coderz
source share