Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

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??

like image 330
AndrewL64 Avatar asked Apr 09 '15 22:04

AndrewL64


People also ask

How do you find the sum of all numbers between 1 and n?

The formula for the sum of the first n positive integers is n(n+1)/2. This formula works for consecutive integers. Thanks!

Is there a sum function in JavaScript?

sum() function in D3. js is used to return the sum of the given array's elements. If the array is empty then it returns 0. Parameters: This function accepts a parameters Array which is an array of elements whose sum are to be calculated.

What is sum += in JavaScript?

The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator.


1 Answers

Your code is fine.

Keep it simple:

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

Wiki.

like image 79
Amir Popovich Avatar answered Oct 16 '22 18:10

Amir Popovich