Given a positive integer X, how can one partition it into N parts, each between A and B where A <= B are also positive integers? That is, write
X = X_1 + X_2 + ... + X_N
where A <= X_i <= B and the order of the X_is doesn’t matter?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here is a python solution to this problem, This is quite un-optimised but I have tried to keep it as simple as I can to demonstrate an iterative method of solving this problem.
The results of this method will commonly be a list of max values and min values with maybe 1 or 2 values inbetween. Because of this, there is a slight optimisation in there, (using
abs) which will prevent the iterator constantly trying to find min values counting down from max and vice versa.There are recursive ways of doing this that look far more elegant, but this will get the job done and hopefully give you an insite into a better solution.
SCRIPT:
The basic idea behind this script is that the value needs to fall between
min*partsandmax*parts, for each step of the solution, if we always achieve this goal, we will eventually end up atmin < value < maxforparts == 1, so if we constantly take away from the value, and keep it within thismin < value < maxrange we will always find the result if it is possable.For this code’s example, it will basically always take away either
maxormindepending on which bound thevalueis closer to, untill some nonminormaxvalue is left over as remainder.