DEV Community

Timothy Huang
Timothy Huang

Posted on • Edited on

Sum of nature numbers with JavaScript (3 ways)

There are many ways to calculate sum of nature numbers. The basic method is for-loop (a simple way):

function sum1(n){
  var sum = 0;
  for(var i=1;i<=n;i++){
    sum += i;
  }
  return sum;
}
Enter fullscreen mode Exit fullscreen mode

Another method is recursion. Since the sum is 1 + 2 + .. + n, we can easily get

sum(n) = n + sum(n-1)
and sum(n-1) = n-1 + sum(n-2) ...
until sum(1) = 1.

This also is a divide-and-conquer method.

function sum2(n){
  if(n==1){
    return 1;
  }else{
    return n + sum2(n-1);
  }
}
Enter fullscreen mode Exit fullscreen mode

The third way is more complex, using map and reduce. With JavaScript, the map function and reduce function are Array methods.

First, we can use map function to create an array as [1, 2, ... n] :

[...Array(n)]
    .map(function(_, index){ 
      return index + 1; 
    })
Enter fullscreen mode Exit fullscreen mode

Second, we can use reduce function to calculate the sum of these numbers:

[...Array(n)]
    .map(function(_, index){ 
      return index + 1; 
    })
    .reduce(function(acc, cur){
      return acc + cur;
    });
Enter fullscreen mode Exit fullscreen mode

Let's play with repl.it:

https://repl.it/@timhuangt/sumOfNatureNumbers

Happy coding!

Top comments (0)