如何使用 JavaScript 查找 1 和 N 之间所有数字的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29549836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the sum of all numbers between 1 and N using JavaScript
提问by AndrewL64
I'm trying to find a way to calculate the sum of all numbers between 1 to N using JavaScript. The following is the code I have tried so far but it doesn't seem to work.
我试图找到一种方法来使用 JavaScript 计算 1 到 N 之间所有数字的总和。以下是我迄今为止尝试过的代码,但似乎不起作用。
function numberSum(N) {
var total = 0;
for(var i = 1; i <= N; i++){
total += i;
}
return total;
}
I have tried using jslint and other validators online to check if I might have missed something but that doesn't seem to help me find the reason for the code not working either. Is there something that I'm missing above that's preventing the script from executing the addition??
我曾尝试在线使用 jslint 和其他验证器来检查我是否可能遗漏了某些内容,但这似乎也无法帮助我找到代码不起作用的原因。上面有什么我遗漏的东西会阻止脚本执行添加吗?
回答by Amir Popovich
回答by A.J. Uppal
Your code runs fine. How did you run it?
您的代码运行良好。你是怎么运行的?
Demo:
演示:
function numberSum(N) {
var total = 0;
for(var i = 1; i <= N; i++){
total += i;
}
return total;
}
function run(){
val = document.getElementById("val").value;
document.getElementById("results").innerHTML=val+": "+numberSum(val)
}
<input id="val">
<input type="Submit" onclick="run();">
<p id="results"></p>
回答by HansDev
I know this is already solved but I wanted to post a quick ES6 oneliner I wrote after reading this thread and explain it more thoroughly for others who like me don't have a solid math background.
我知道这已经解决了,但我想发布一个我在阅读此线程后写的快速 ES6 oneliner,并为像我这样没有扎实数学背景的其他人更彻底地解释它。
const numSum = (n) => n * (n+1) / 2;
It works because it uses a mathematic formula that Carl Friedrich Gauss came up with. (this has a great image).
它之所以有效,是因为它使用了卡尔·弗里德里希·高斯 (Carl Friedrich Gauss) 提出的数学公式。(这有一个伟大的形象)。
Basically, whenever you are adding the sum of n numbers, you will have pairs in the sequence. So Gauss figured out that you didn't need to loop through each pair and add them, instead you just need to add the middle pair and multiply that sum by the total number of pairs. This works really well for programming because they aren't looping through each number which in programming would eat through your resources.
基本上,每当您添加 n 个数字的总和时,序列中都会有对。所以 Gauss 发现你不需要遍历每一对并将它们相加,相反你只需要添加中间对并将该总和乘以对的总数。这对编程非常有效,因为它们不会循环遍历每个数字,这在编程中会消耗您的资源。
You can find the number of pairs by dividing n/2 and it also gives you the middle number then you just add 1 to find its pair.
您可以通过除以 n/2 来找到对的数量,它还为您提供中间数字,然后您只需添加 1 即可找到它的对。
Let say you are getting the sum of 1-100, by applying Gauss's approach, you'd want 50(101)=5050. 50 is the number of pairs and in the code, it is represented by n *and 101 is the addition of the middle pair (50+51) or in the code (n+1), then finally we divide by 2 for the middle number.
假设您得到 1-100 的总和,通过应用高斯方法,您需要 50(101)=5050。50 是对数,在代码中用n *101表示中间对的加法 (50+51) 或者在代码中(n+1),最后除以 2 表示中间数。
回答by Neil Meyer
function SimpleAdding(num) {
place = 1;
i = num;
do {place = place += i; i--}
while (i > 1);
return place;
}
You set your placeholder variable equal to one. You also set the number of iterations equal to the input variable.
您将占位符变量设置为等于 1。您还将迭代次数设置为等于输入变量。
The do loop then adds your placeholder variable with 'i' and then the loop exits when it is no longer greater than 1, which is correct because you have your placeholder equal to one.
然后 do 循环添加带有 'i' 的占位符变量,然后当它不再大于 1 时循环退出,这是正确的,因为您的占位符等于 1。
回答by antonjs
It can be calculated by using the recursion
可以使用递归计算
var numberSum = (n, a = n) => n ? numberSum(n = n - 1 , a = a + n) : a
回答by Interesting-Diva
function numSum(n){
var sum = 0;
for(i = 0; i <= n; i++){
sum += i;
}
console.log(sum)
}
numSum(15);
回答by MoeSattler
More general answer with recursion.
更一般的递归答案。
const sumRange = (min, max) => min !== max
? sumRange(min, max - 1) + max
: 0
While this might not be the most optimal answer for the case of min:0 max:n, it might be the easiest to read and understand.
虽然这可能不是 min:0 max:n 情况下的最佳答案,但它可能是最容易阅读和理解的。

