Armstrong numbers in JavaScript
Intermediate · 4 min read
153 has a curious property. Take each of its digits, cube it, and add the results: 1 + 125 + 27 = 153. You get the number back. Numbers like this are called Armstrong numbers (also narcissistic numbers), and finding them is a classic beginner exercise.
There is one detail many tutorials get wrong: the power isn't always 3. It is the number of digits. A three-digit number uses cubes, a four-digit number uses fourth powers, and so on. In this tutorial you will write isArmstrong(n), start with the fixed-cube version to see where it goes wrong, and then find every Armstrong number below 100000. You need to know arrays, map and reduce.
Splitting a number into digits
The easiest way to get the digits is to go through a string. String(153) is '153', split('') breaks it into characters, and map(Number) turns each character back into a number.
console.log(String(153).split('')); // [ '1', '5', '3' ]
console.log(String(153).split('').map(Number)); // [ 1, 5, 3 ]
Powers with **
** raises a number to a power. 5 ** 3 is 5 times 5 times 5, which is 125. d ** 1 is just d.
Adding up with reduce
reduce walks through an array and keeps a running total. reduce((acc, d) => acc + d, 0) starts at 0 and adds each item to acc in turn.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
49 Armstrong numbers
fairAn Armstrong number equals the sum of its digits each raised to the count of digits: 153 = 1³ + 5³ + 3³. Find all of them below 10000, show there are none with two digits, and find the three with five.
Stuck? Three hints, smallest first
- 1. The exponent is the number of digits, not a fixed 3.
- 2. Get the digit count once, then raise each digit to it.
- 3. The two-digit case can be argued rather than searched: no sum of two squared digits reaches a two-digit number that matches.
Step 1: the cube version
Many people write this first, because the famous example 153 uses cubes:
const cubeSum = (n) => String(n).split('').reduce((acc, c) => acc + Number(c) ** 3, 0);
console.log(cubeSum(153)); // 153
console.log(cubeSum(154)); // 190
console.log([370, 371, 407].map(cubeSum)); // [ 370, 371, 407 ]
153 gives itself back. So do 370, 371 and 407. 154, one more than 153, gives 190, so it isn't one.
Step 2: the four-digit number it misses
Now try 9474:
console.log(cubeSum(9474)); // 1200
console.log(9 ** 4 + 4 ** 4 + 7 ** 4 + 4 ** 4); // 9474
With cubes, 9474 gives 1200. With fourth powers, it gives 9474. 9474 has four digits, so the right power is 4, and it is an Armstrong number. The cube version answers a different question: "which numbers equal the sum of the cubes of their digits?". The answer to that is only 153, 370, 371 and 407 (plus 0 and 1).
Step 3: use the digit count as the power
function isArmstrong(n) {
const digits = String(n).split('').map(Number);
const power = digits.length;
const sum = digits.reduce((acc, d) => acc + d ** power, 0);
return sum === n;
}
console.log(isArmstrong(153)); // true
console.log(isArmstrong(9474)); // true
console.log(isArmstrong(154)); // false
We work out the digit count once, store it in power, and raise every digit to it. This is the answer's version.
Step 4: every Armstrong number below 10000
const below10000 = [];
for (let n = 0; n < 10000; n++) if (isArmstrong(n)) below10000.push(n);
console.log(below10000.join(', ')); // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474
Every single digit qualifies, because a one-digit number uses power 1, and d ** 1 is d. Then come the four three-digit ones, then three with four digits: 1634, 8208 and 9474.
Step 5: none with two digits
const twoDigit = below10000.filter((n) => n >= 10 && n < 100);
console.log(twoDigit); // []
There are no two-digit Armstrong numbers at all. A two-digit number with digits a and b is worth 10 times a plus b, and the power is 2, so the sum it would have to match is a squared plus b squared. There are only 90 two-digit numbers, and the search checks every one of them: none match. 10, for example, gives 1 squared plus 0 squared, which is 1.
Step 6: the five-digit ones
const fiveDigit = [];
for (let n = 10000; n < 100000; n++) if (isArmstrong(n)) fiveDigit.push(n);
console.log(fiveDigit); // [ 54748, 92727, 93084 ]
Three of them. You can check one by hand: 9 to the 5th is 59049, 2 to the 5th is 32, 7 to the 5th is 16807, so 92727 is 59049 + 32 + 16807 + 32 + 16807, which is 92727.
Armstrong numbers don't go on forever. A k-digit number is at least 10 to the power k - 1, but the largest digit sum it can reach is k times 9 to the power k, and that eventually falls behind. They stop at 39 digits.
The full solution
The answer panel has isArmstrong and the fixed-cube cubeSum, then prints 153 as cubes, every Armstrong number below 10000, the empty two-digit list, the five-digit ones, and 9474 both ways. Press Run to see the output.
function isArmstrong(n) {
const digits = String(n).split('').map(Number);
const power = digits.length;
const sum = digits.reduce((acc, d) => acc + d ** power, 0);
return sum === n;
}
const below10000 = [];
for (let n = 0; n < 10000; n++) if (isArmstrong(n)) below10000.push(n);
const twoDigit = below10000.filter((n) => n >= 10 && n < 100);
const fiveDigit = [];
for (let n = 10000; n < 100000; n++) if (isArmstrong(n)) fiveDigit.push(n);
// The same digits with a fixed exponent of 3 answer a different question.
const cubeSum = (n) => String(n).split('').reduce((acc, c) => acc + Number(c) ** 3, 0);
console.log('153 as cubes :', [1 ** 3, 5 ** 3, 3 ** 3], 'summing to', cubeSum(153));
console.log('below 10000 :', below10000);
console.log('two-digit ones:', twoDigit);
console.log('five-digit :', fiveDigit);
console.log('9474 as fourth powers:', [9 ** 4, 4 ** 4, 7 ** 4, 4 ** 4].reduce((a, b) => a + b, 0));
console.log('but 9474 as cubes :', cubeSum(9474));
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('153 is the sum of the cubes of its digits', [cubeSum(153), isArmstrong(153)], [153, true]);
test('370, 371 and 407 are the other three-digit ones', [370, 371, 407].every(isArmstrong), true);
test('154 is not, being one away', [isArmstrong(154), cubeSum(154)], [false, 190]);
test('every Armstrong number below 10000', below10000, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]);
test('every single digit qualifies, since d to the power 1 is d', [0, 1, 5, 9].every(isArmstrong), true);
test('and there are none at all with two digits', twoDigit, []);
test('9474 works because the exponent follows the digit count', [9 ** 4 + 4 ** 4 + 7 ** 4 + 4 ** 4, cubeSum(9474)], [9474, 1200]);
test('three five-digit ones exist', fiveDigit, [54748, 92727, 93084]);
test('and 9474 is not one of them under a fixed cube', isArmstrong(9474) && cubeSum(9474) !== 9474, true);
The exponent is the whole exercise. Fix it at 3 and you are asking a different question — the numbers equal to the sum of the cubes of their digits, which are 153, 370, 371 and 407 and nothing else. Let it follow the digit count and the family continues: 1634 and 8208 and 9474 with fourth powers, three more with fifth. It stops at 39 digits, because 9 ** k * k eventually falls behind 10 ** (k - 1).
The two-digit gap has a short proof. A two-digit number is 10a + b and the candidate sum is a² + b²; the largest that sum can be is 81 + 81 = 162, and checking the ninety cases is quick, but the useful observation is that a² + b² grows too slowly in a to keep up with 10a. The search above confirms the answer rather than establishing it.
Common mistakes
- Fixing the power at 3. That works for 153 but misses 1634, 8208 and 9474. Use the digit count.
- Counting digits inside the loop. It works, but it repeats the same work for every digit. Work out
poweronce. - Forgetting
Number(c).'5' ** 3happens to work because**converts strings, but'5' + '3'gives'53'. Convert digits before you add them.
Try it yourself
- Write
armstrongSum(n)that returns the sum instead oftrueorfalse, and print it for 100 to 110. - Rewrite
isArmstrongwithout strings, using% 10andMath.floor(n / 10)to get the digits. - Count how many Armstrong numbers exist below 1000000. (Hint: search the six-digit numbers.)