拆分自然数:纯while实现 (Part 2 - 实现)
2010-09-14 13:47:48 来源:WEB开发网function main(m, n, min, max) {
var array = new Array(n);
var i = 0;
var write = function() {
console.log(m + ' = ' + array.join(' + '));
};
var scan = function() {
if (scan.start) {
scan.start = false;
scan.sum = 0;
}
scan.sum += array[i];
return (array[i] > array[n - 1] - 2);
};
var step = function() {
array[i]++;
fill.sum = scan.sum - array[i];
i++;
};
var fill = function() {
while (i < n) {
array[i] = Math.max((fill.sum - (n - i - 1) * max), ((i == 0) ? min : array[i - 1]));
fill.sum -= array[i];
i++;
}
i--;
};
fill.sum = m;
fill();
write();
while (true) {
scan.start = true;
while (i >=0 && scan()) {
i--;
}
if (i < 0) {
break;
}
step();
fill();
write();
}
}
更多精彩
赞助商链接