How do I divide a large positive integer n into m parts uniformly randomly. Post-condition: Adding up all the m parts should give n.
Below is my attempt(in java like pseudocode), but I don't think it will give me uniformly random distribution. I am first finding the average part avg by dividing n/m. Then I am generating m-1 random numbers which are around avg in magnitude(by alternately generating random numbers between 0 & avg, and *avg & 2*avg*. Then I am subtracting the sum of these m-1 numbers from original number n and setting that as the m'th part.
Assume that the function rand(x, y) returns a random number uniformly between x and y.
int[] divideUniformlyRandomly(int n, int m)
{
int[] res = new int[m];
int avg = n / m;
int sum = 0;
bool alternator = false;
for(int i = 0; i < m - 1; i++)
{
if(alternator == false)
{
res[i] = rand(0, avg);
alternator = true;
}
else
{
res[i] = rand(avg, 2*avg);
alternator = false;
}
sum += res[i];
}
res[m-1] = n - sum;
return res;
}