title: Divide a number into unequal parts in order to balance vector in r
body: <p>I have a vector made of 10 random integers like this:</p>
  <p><code>a &lt;- c(400,1,1,1,1,1,1,1,1,13)</code></p>
  <p>and I have a random integer:</p>
  <p><code>n &lt;- 100</code></p>
  <p>My goal is to divide <code>n</code> so that the components of <code>a</code> have the smallest differences between them. The desired output in this case is <code>c(400,14,14,14,14,13,13,13,13,13)</code> (13+13+13+13+12+12+12+12 = 100)</p>
  <p>My approach was to use a recursive function:</p>
  <pre><code>    dis &lt;- function(n,a){
  
        a[which.min(a)] &lt;- a[which.min(a)] + 1 
  
        n &lt;- n -1
  
        if(!n){
          return(a)
        }
  
        dis(n,a)
  
     }
  
     dis(100, c(400,1,1,1,1,1,1,1,1,13))
  </code></pre>
  <p>But I found problems when <code>n</code> is larger, e.g. when <code>n</code> is 1000 I get this message</p>
  <blockquote>
  <p>Error: C stack usage  7969684 is too close to the m</p>
  </blockquote>
  <p>I'm not sure if there is something to avoid recursion, maybe an arithmetic solution, or another approach.</p>