DEV Community

Timothy Huang
Timothy Huang

Posted on • Edited on

1

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!

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay