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??
The formula for the sum of the first n positive integers is n(n+1)/2. This formula works for consecutive integers. Thanks!
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.
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.
Your code is fine.
Keep it simple:
var res = (n * (n+1)) / 2;
Wiki.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With