How to find the sum of all numbers between 1 and N using JavaScript

Your code is fine.

Keep it simple:

var res = (n * (n+1)) / 2;

Wiki.


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>

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.

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).

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.

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.

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.