var all = 21; var people = [0,0,0,0,0]; for(var i=1;i<=people.length;i++){ people[i-1] = i; all -= i; } var start = people.length-1; while(all>0){ people[start]++; all--; start--; if (start<=0) {start = people.length-1}; } alert(people[people.length-1])