This blog post is going to focus on solving the sum of N numbers. It's a typical question that could pop up in a Junior interview, or potentially in your college work. So the question could be what is the sum of the first 1000 numbers.

Using Loops to solve the problem.

We could solve this using a for loop passing in N into the function. For Example:

```
function findSum(n) {
let result = 0;
for (let i = 1; i <= n; i++) {
result = result + i;
}
return result;
}
let n = 1000;
console.log(`Sum of the numbers from 1 to ${n} is ${findSum(n)}`);
```

This will solve the problem, and the result will be 500500 but it is quite inefficient because as the number gets bigger so does the iteration and memory usage.

Thinking of this problem like a maths problem.

So the problem we are attempting to solve is:

```
sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + ... n
```

If we think of it, we are technically just doing:

```
sum = n + (n-1) + (n-2) + (n-3) + (n-4) + (n-5) ... +1
```

There is an arithmetic solution for this called Arithmetic progression which is described as a sequence of numbers such that the difference between the consecutive terms is constant.

To break it down, let's look at this very simple example:

```
2+5+8+11+14
```

This sum can be found quickly by taking the number n of terms being added (here 5), multiplying by the sum of the first and last number in the progression (here 2 + 14 = 16), and dividing by 2:

```
(n(a1 + a2))/2
```

Which means we can solve this in a single line of JavaScript, by using what we know from our Maths problem:

```
function findSum(n) {
return (n * (n + 1)) / 2;
}
let n = 1000;
console.log(`Sum of the numbers from 1 to ${n} is ${findSum(n)}`);
```

Using this we get the same result, and it doesn't matter how big the number is as we aren't iterating, we are directly calculating the solution.

I hope you enjoyed the short tutorial on calculating the sum of n numbers, and I hope it helps when you are prepping for some interviews.

## Top comments (0)