Triangular numbers and series sums in JavaScript
Intermediate · 4 min read
Add up 1 + 2 + 3 + ... + 100. You could write a loop, or you could use a formula that gives 5050 in one line. The numbers you get by adding 1 up to n are called triangular numbers, because that many dots can be stacked into a triangle: 1 dot, then 3, then 6, then 10.
Formulas like this one, called closed forms, replace a loop with a single calculation. They are used for totals in finance, for counting handshakes or pairs, and for working out the size of a growing series without adding every term. In this tutorial you will write the triangular formula, test whether a number is triangular, and then write closed forms for two kinds of series: ones that add the same amount each time and ones that multiply by the same amount. You need to know loops, functions and **.
The pairing trick
Write the numbers 1 to 100 forwards, and underneath write them backwards. Each column adds up to 101: 1 + 100, 2 + 99, and so on. There are 100 columns, so both rows together make 100 times 101. One row is half of that, 5050.
The same idea works for any n: the sum of 1 to n is n * (n + 1) / 2.
Two kinds of series
An arithmetic series adds the same step each time: 3, 8, 13, 18 (step 5). A geometric series multiplies by the same ratio each time: 1, 2, 4, 8 (ratio 2). Each has its own closed form, which you will build below.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
51 Triangular numbers, and series sums in closed form
fairSum 1 to n without a loop, then generalise to any arithmetic and geometric series. Test whether a number is triangular, and find where the closed form leaves exact-integer range.
Stuck? Three hints, smallest first
- 1.
n * (n + 1) / 2, and the division is exact because one of the two is always even. - 2. A number
tis triangular exactly when8t + 1is a perfect square. - 3. The geometric formula divides by
r - 1, sor === 1needs its own branch.
Step 1: the loop, to check against
const triangularByLoop = (n) => {
let sum = 0;
for (let k = 1; k <= n; k++) sum += k;
return sum;
};
console.log(triangularByLoop(100)); // 5050
This is slow for big n but easy to trust. We will use it to check the formula.
Step 2: the closed form
const triangular = (n) => (n * (n + 1)) / 2;
console.log([0, 1, 2, 3, 4, 5, 6, 7].map(triangular)); // [ 0, 1, 3, 6, 10, 15, 21, 28 ]
console.log(triangular(1000), triangularByLoop(1000)); // 500500 500500
Is the division by 2 always exact? Yes. Of any two numbers in a row, n and n + 1, one is even. So their product is always even, and halving it gives a whole number.
Step 3: is a number triangular?
There is a neat test: a number t is triangular exactly when 8 * t + 1 is a perfect square. For 10, 8 * 10 + 1 is 81, which is 9 squared. For 7, it is 57, which isn't a square.
const isPerfectSquare = (n) => {
const r = Math.round(Math.sqrt(n));
return r * r === n;
};
const isTriangular = (t) => t >= 0 && isPerfectSquare(8 * t + 1);
console.log([1, 3, 6, 10, 28].every(isTriangular)); // true
console.log([2, 4, 5, 7, 29].some(isTriangular)); // false
The square test rounds the root and multiplies back, so it compares whole numbers only.
Step 4: an arithmetic series
For n terms starting at a with step d, the pairing trick still works: the first and last terms add to the same total as the second and second-to-last. The last term is a + (n - 1) * d, so the sum is n times (first plus last), halved:
const arithmeticSum = (a, d, n) => (n * (2 * a + (n - 1) * d)) / 2;
console.log(arithmeticSum(3, 5, 10)); // 255
console.log(arithmeticSum(1, 1, 100)); // 5050
The second line is the triangular number again: start at 1, step 1.
Step 5: a geometric series, and its hole
For n terms starting at a with ratio r, the closed form is a * (r ** n - 1) / (r - 1). For 1 + 2 + 4 + ... with ten terms:
console.log((1 * (2 ** 10 - 1)) / (2 - 1)); // 1023
That is one short of 1024, the next power of two. Now try a ratio of 1, where every term is the same, for example 5 + 5 + 5 + 5:
console.log((5 * (1 ** 4 - 1)) / (1 - 1)); // NaN
The formula divides 0 by 0. The true answer is obviously 20. A ratio of 1 isn't covered by the formula at all, so it needs its own branch:
const geometricSum = (a, r, n) => (r === 1 ? a * n : (a * (r ** n - 1)) / (r - 1));
console.log(geometricSum(5, 1, 4)); // 20
console.log(geometricSum(1, 2, 10)); // 1023
Step 6: halves add up exactly
Try the ratio 0.5: 1 + 1/2 + 1/4 + ... With ten terms, compare the formula with adding term by term:
const geometricByLoop = (a, r, n) => {
let sum = 0;
let term = a;
for (let k = 0; k < n; k++) {
sum += term;
term *= r;
}
return sum;
};
console.log(geometricSum(1, 0.5, 10)); // 1.998046875
console.log(geometricByLoop(1, 0.5, 10)); // 1.998046875
They agree exactly. Computers store numbers in binary, and halves, quarters and eighths are exact in binary, so there is no rounding at all. With 100 terms the loop lands exactly on 2, the value the series gets closer and closer to. A ratio like 1/3 is not exact in binary, so it wouldn't behave this nicely.
Step 7: where the formula stops being exact
console.log(triangular(200000000)); // 20000000100000000
console.log(Number.isSafeInteger(triangular(200000000))); // false
T(200000000) is past Number.MAX_SAFE_INTEGER, about 9 million billion. Above that, JavaScript can't store every whole number, so the result may be rounded. For sums that large, use BigInt.
The full solution
The answer panel has triangular and its loop, isTriangular, both series formulas and the geometric loop, then prints the first eight triangular numbers, T(100), T(1000), T(2e8), both series examples, the halves sum and the unguarded ratio-of-1 case. Press Run to see the output.
const triangular = (n) => (n * (n + 1)) / 2;
const triangularByLoop = (n) => {
let sum = 0;
for (let k = 1; k <= n; k++) sum += k;
return sum;
};
const isPerfectSquare = (n) => {
const r = Math.round(Math.sqrt(n));
return r * r === n;
};
const isTriangular = (t) => t >= 0 && isPerfectSquare(8 * t + 1);
// n terms starting at a, step d.
const arithmeticSum = (a, d, n) => (n * (2 * a + (n - 1) * d)) / 2;
// n terms starting at a, ratio r. r === 1 is not a special case of the formula.
const geometricSum = (a, r, n) => (r === 1 ? a * n : (a * (r ** n - 1)) / (r - 1));
const geometricByLoop = (a, r, n) => {
let sum = 0;
let term = a;
for (let k = 0; k < n; k++) {
sum += term;
term *= r;
}
return sum;
};
let towardsTwo = 0;
let term = 1;
for (let k = 0; k < 100; k++) {
towardsTwo += term;
term /= 2;
}
console.log('first eight :', [0, 1, 2, 3, 4, 5, 6, 7].map(triangular));
console.log('T(100), T(1000):', triangular(100), triangular(1000));
console.log('T(2e8) :', triangular(200000000), 'safe?', Number.isSafeInteger(triangular(200000000)));
console.log('3, 8, 13, ... x 10:', arithmeticSum(3, 5, 10));
console.log('1 + 2 + 4 + ... :', geometricSum(1, 2, 10));
console.log('1 + 1/2 + ... :', geometricSum(1, 0.5, 10), 'and 100 terms give', towardsTwo);
console.log('r === 1 unguarded:', (5 * (1 ** 4 - 1)) / (1 - 1));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the first eight triangular numbers', [0, 1, 2, 3, 4, 5, 6, 7].map(triangular), [0, 1, 3, 6, 10, 15, 21, 28]);
test('T(100) is 5050 and T(1000) is 500500, matching the loop', [triangular(100), triangular(1000), triangularByLoop(1000)], [5050, 500500, 500500]);
test('8t + 1 being square identifies them', [[1, 3, 6, 10, 28].every(isTriangular), [2, 4, 5, 7, 29].some(isTriangular)], [true, false]);
test('an arithmetic series in closed form', [arithmeticSum(3, 5, 10), arithmeticSum(1, 1, 100)], [255, 5050]);
test('ten powers of two sum to 1023, one short of 1024', [geometricSum(1, 2, 10), 2 ** 10 - 1], [1023, 1023]);
test('halves are exact in binary, so the formula and the loop agree exactly', [geometricSum(1, 0.5, 10), geometricByLoop(1, 0.5, 10)], [1.998046875, 1.998046875]);
test('and 100 terms land exactly on 2, the limit', towardsTwo, 2);
test('a ratio of 1 would divide by zero, hence the branch', [geometricSum(5, 1, 4), Number.isNaN((5 * (1 ** 4 - 1)) / (1 - 1))], [20, true]);
test('T(2e8) is past 2 ** 53, so the closed form stops being exact', [triangular(200000000), Number.isSafeInteger(triangular(200000000))], [20000000100000000, false]);
n * (n + 1) / 2 is safe to write as a division rather than a multiplication by 0.5: consecutive integers include an even one, so the numerator is always even and the result is exact. That stops being the point at around n = 1.34e8, where the product itself passes 2 ** 53 and the answer is merely close.
Two things about the geometric form. The r === 1 branch is not defensive programming, it is a genuine hole in the formula: (r ** n - 1) / (r - 1) is 0 / 0 there. And the halves case is a reminder that floating point is not always lossy — 0.5, 0.25 and their sums are exact binary fractions, so the closed form and the term-by-term loop agree to the last bit, which they would not for a ratio of 1 / 3.
Common mistakes
- Dividing by
r - 1whenris 1. You get 0 / 0, which isNaN. Handler === 1separately asa * n. - Writing
n * (n + 1) / 2with the wrong grouping.n * n + 1 / 2is something else entirely. Keep the brackets. - Assuming the formula is exact for any n. Past the safe-integer limit, results can be rounded.
Try it yourself
- Ten people in a room all shake hands once with each other. How many handshakes? (Hint: it is
triangular(9).) - Use
arithmeticSumto add up all the odd numbers from 1 to 99. Compare with 50 squared. - Try
geometricSum(1, 1 / 3, 20)andgeometricByLoop(1, 1 / 3, 20). Do they match exactly?