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

I am trying to find a way to calculate the sum of all numbers from 1 to N using JavaScript. Below is the code I tried so far, but it does not work.

function numberSum(N) {
  var total = 0;
    for(var i = 1; i <= N; i++){
      total += i;
    }
    return total;
}

I tried using jslint and other validators online to check if I could miss something, but this does not seem to help me find the reason why the code is not working. Is there something I am missing that prevents the script from completing the append?

+6
source share
6 answers

Your code is ok.

Keep it simple:

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

Wiki edits .

+34
source

Your code is working 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>
Run codeHide result
+6
source

function SimpleAdding(num) { 
 
  place = 1;
  i = num;
  do {place = place += i; i--}
  while (i > 1);
  return place; 
         
}
Hide result

, . , .

Then the do loop adds your placeholder variable to "i", and then the loop exits when it is no more than 1, which is correct because you have a placeholder equal to one.

0
source

It can be calculated using recursion

var numberSum = (n, a = n) => n ? numberSum(n = n - 1 , a = a + n) : a
0
source
function numSum(n){
    var sum = 0;
      for(i = 0; i <= n; i++){
        sum += i; 
         }
    console.log(sum)
         }
numSum(15);
-1
source

A more general answer with recursion.

const sumRange = (min, max) => min !== max 
    ? sumRange(min, max - 1) + max 
    : 0

Although this may not be the best answer for the case min: 0 max: n, it may be easiest to read and understand.

-1
source

Source: https://habr.com/ru/post/1690359/


All Articles