Skip to content
Jabran Rafique

Sum of consecutive numbers (Maths series)

1 minute read

Maths meets programming

Helping my son prepare for the 11+ test got me interested in maths again. I've been programming for over 20 years, so I kept turning the formulas we covered into code. These posts are my notes from that.

These problems are simple and you'll find them solved on plenty of coding sites. This is just me working through them.

The task: add up n consecutive numbers. For 1,2,3,4,5 that's 1 + 2 + 3 + 4 + 5 = 15.

Problem

With five numbers it's easy. With a few hundred it gets tedious fast.

Solution

My first thought for 1, 2, 3, ..., n was to loop through the numbers. You don't need to. This formula does it in one step:

x = n ( n + 1 ) 2

n is the largest number in the list, so for 1,2,3,4...100, n = 100.

In JavaScript:

function sum(...args) {
  const n = Math.max(...args);
  return (n * (n + 1)) / 2;
}

Example:

sum(1, 2, 3, 4, 5); // 15

Others in the Maths series