将1、2、3、……、n这n个连续自然数分成g组,使每组的和相等。g组中个数最多的一组有几个?

时间:2022-12-18 13:00:56
<style type="text/css">
#content {
width: 600px;
margin: 150px auto 0 auto;
} dl dd {
height: 26px;
line-height: 26px;
} dl dd label {
width: 220px;
display: inline-block;
} dl button {
margin-left: 228px;
}
</style>
<div id="content">
<dl>
<dt>将1+2+3+n个连续自然数分成g组,使每组的和相等。g组中个数最多的一组有几个?</dt>
<dd>
<label>请输入总数(n):</label>
<input type="text" name="total" id="total" value="" />
</dd>
<dd>
<label>请输入分组数(g):</label>
<input type="text" name="" id="group" value="" />
</dd>
<dd>
<label>和为:</label>
<input type="text" name="" id="sum" value="" disabled="disabled" />
</dd>
<dd>
<label>计算出的平均数:</label>
<input type="text" name="avg" id="avg" value="" disabled="disabled" />
</dd>
<dd>
<label>g组中个数最多的一组数目为:</label>
<input type="text" id="mostCount" disabled="disabled" />
</dd>
<dd>
<button id="btn">计算</button>
</dd>
</dl> </div>
<script type="text/javascript">
document.getElementById("btn").onclick = function() {
var n = document.getElementById("total").value,
group = document.getElementById("group").value,
sum,
avg,
thisSum = 0; // 前n个数的和
if (!n || !group) {
alert("请输入总数和组数。")
return;
}
sum = n * (+n + 1) / 2;
avg = sum / group;
document.getElementById("sum").value = sum;
document.getElementById("avg").value = avg;
for (var i = 1; i <= n; i++) {
thisSum += i;
if (thisSum > avg) {
document.getElementById("mostCount").value = i - 1;
break;
}
}
}
</script>