- Digits
- 3, so exponent 3
- Sum
- 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
- Verdict
- Equals
n— Armstrong.
Check Armstrong Number in JavaScript
What you’ll learn
- The Armstrong (narcissistic) condition in base 10: sum of each digit raised to the number of digits.
- A precise algorithm, pseudocode, and two JavaScript examples: one number and a range scan, plus Try it Yourself links.
- Why a small integer-style power loop beats
Math.powfor exact checks, plus edge cases and complexity. - A browser live preview that mirrors the same digit-power rule.
Overview
An Armstrong number equals the sum of its decimal digits, each raised to the power of how many digits it has. Classic example: 153 = 1³ + 5³ + 3³. This tutorial shows how to implement that test in JavaScript, then scan a range.
Two programs
A single-value check (try 153) and a range listing (same idea as 1 to 200 in the reference).
Live preview
See digit count k, the expanded sum of each dk, and the verdict without compiling.
Interview polish
Guards for n ≤ 0, integer powers, overflow notes, and complexity in one place.
Prerequisites
Comfort with loops, integer division, and the modulo operator % is enough to follow the code.
- JavaScript basics:
function,const/let,console.log, and integer division withMath.floor. - Extracting the last digit with
n % 10and shifting withn / 10. - Optional: comparing this idea to amicable and abundant problems (different rules, same “loop over structure of
n” pattern).
What is an Armstrong number?
Let n be a positive integer with k decimal digits. Write those digits as dk-1 … d1 d0 (most significant to least). Then n is an Armstrong number (in base 10) when
dk-1k + … + d1k + d0k = n.
The exponent is always the digit count, not the value of the digit. Same idea generalizes to other bases; here we stay in decimal.
Mathematical definition
Fix base b = 10. If n has k decimal digits ak-1, …, a0 (most significant to least), then n is Armstrong when ak-1k + … + a0k = n.
For 100 ≤ n ≤ 999, write n = 100a + 10b + c with digits a,b,c. Armstrong means a³ + b³ + c³ = 100a + 10b + c.
Examples: 153, 370, 371, 407 are the only three-digit Armstrong numbers besides the trivial one-digit cases.
Intuition and examples
Count how many digits n has. Peel digits off from the right with % 10 and / 10, raising each peel to that count and adding into a running total. If the total lands back on n, you have an Armstrong number.
Each card shows the digit-power sum with the same exponent k everywhere.
- Digits
- 3, exponent 3
- Sum
- 1³ + 2³ + 3³ = 1 + 8 + 27 = 36
- Verdict
- 36 ≠ 123 — not Armstrong.
- Digits
- 1, exponent 1
- Sum
- 7¹ = 7
- Verdict
- Every 1–9 works the same way.
Takeaway: the exponent is the length of n in decimal, not “how big the digit feels.”
Live preview
Type a positive integer n. The widget counts decimal digits k, builds the sum of each digit to the kth power, and compares it to n. Caps at 999 999 999 to keep JavaScript arithmetic predictable.
- Try 153, 123, or a single digit.
- Press Run check (or Enter).
- Read the expanded sum line and the verdict.
Algorithm
Goal: decide whether a given n is an Armstrong number in base 10.
Validate n
If n ≤ 0, return false (or follow your problem’s convention explicitly).
Count digits k
Copy n to a temporary variable and repeatedly divide by 10 until it becomes 0, counting iterations.
Accumulate digit powers
Walk digits again with % 10 and / 10. Add digit^k to a running sum using exact integer exponentiation.
Compare
If the sum equals the original n, return true; otherwise false.
List Armstrong numbers in [low, high]
Loop i from low to high and print (or collect) each i that passes the four-step test. The core check does not change.
📜 Pseudocode
function digitCount(n):
k ← 0
t ← n
while t > 0:
k ← k + 1
t ← floor(t / 10)
return k
function sumDigitPowers(n, k):
sum ← 0
t ← n
while t > 0:
d ← t mod 10
sum ← sum + (d to the power k) // integer power
t ← floor(t / 10)
return sum
function isArmstrong(n):
if n <= 0:
return false
k ← digitCount(n)
return sumDigitPowers(n, k) = nCheck a single number (program with explanation)
Uses a small intPow helper so every step uses integer-style multiplication—no Math.pow rounding surprises for typical interview inputs.
function intPow(base, exp) {
let r = 1;
for (let e = 0; e < exp; e++) {
r *= base;
}
return r;
}
/** @param {number} number positive integer */
function isArmstrong(number) {
if (number <= 0) {
return false;
}
let k = 0;
let t = number;
while (t > 0) {
k++;
t = Math.floor(t / 10);
}
t = number;
let sum = 0;
while (t > 0) {
const d = t % 10;
sum += intPow(d, k);
t = Math.floor(t / 10);
}
return sum === number;
}
const n = 153;
if (isArmstrong(n)) {
console.log(n + " is an Armstrong number.");
} else {
console.log(n + " is not an Armstrong number.");
}Explanation
Two passes over the digits: first to learn k, second to sum dk for each decimal digit d.
if (number <= 0) return false;Guard non-positive inputs. Digit count is ambiguous for 0, and negatives are not in the usual definition used here.
while (t > 0) { k++; t = Math.floor(t / 10); }Count digits. Integer division by ten strips one decimal digit per iteration.
sum += intPow(d, k);Same exponent for every digit. That is what distinguishes Armstrong numbers from other digit games.
return sum === number;Final comparison against the original value, not the working copy used while peeling digits.
Armstrong numbers in a range
Same isArmstrong helper as Example 1, wrapped in a loop from 1 to 200 (matches the sample output line).
function intPow(base, exp) {
let r = 1;
for (let e = 0; e < exp; e++) {
r *= base;
}
return r;
}
function isArmstrong(num) {
if (num <= 0) {
return false;
}
let k = 0;
let t = num;
while (t > 0) {
k++;
t = Math.floor(t / 10);
}
t = num;
let sum = 0;
while (t > 0) {
const d = t % 10;
sum += intPow(d, k);
t = Math.floor(t / 10);
}
return sum === num;
}
const start = 1;
const end = 200;
console.log("Armstrong numbers in the range " + start + " to " + end + ":");
let line = "";
for (let i = start; i <= end; i++) {
if (isArmstrong(i)) {
line += i + " ";
}
}
console.log(line.trim());Explanation
The outer loop is linear in the width of the interval; the inner test is logarithmic in each i.
for (let i = start; i <= end; i++)Brute enumeration. Change start and end to whatever bounds you need.
if (isArmstrong(i)) line += i + " ";Filter with the same predicate as the single-number script—build a string (or log each hit) instead of printf.
Optimization
Exponentiation. For fixed digit count k, precompute 0^k … 9^k in a table of length 10 and replace intPow(d,k) with a lookup when scanning many numbers.
Bounds on sums. For a given k, the maximum digit-power sum is 9^k · k. Prune candidate n values outside plausible intervals when generating large lists.
Wide integers. Promote the accumulator to BigInt (and use BigInt(n) for comparisons) if powers can exceed safe integer range.
Interview: state the O(log n) digit pass clearly; mention lookup tables only if they ask for faster range generation.
❓ FAQ
🔄 Input / output examples
For the single-number script with a literal n, typical lines look like this. Swap in process.argv or a prompt if you want interactive input.
Value of n | Typical line printed |
|---|---|
| 153 | 153 is an Armstrong number. |
| 123 | 123 is not an Armstrong number. |
| 7 | 7 is an Armstrong number. |
| 0 | 0 is not an Armstrong number. (with the sample guard) |
For the range program with start = 1 and end = 200:
Armstrong numbers in the range 1 to 200:
1 2 3 4 5 6 7 8 9 153Edge cases and pitfalls
Most bugs come from miscounting digits, reusing a mutated copy of n, or mixing floating-point Math.pow into an integer-style test.
n ≤ 0
Return false early. Otherwise 0 can slip through with a digit count of 0 in naive loops.
Losing the original n
Keep one variable for comparison and separate temporaries for counting and summing, or reassign from a saved copy.
Math.pow rounding
Using Math.pow then rounding can be off by one for some values. Prefer a small integer multiply loop (or BigInt powers) for exact equality tests.
Partial sums
Digit powers add up quickly. Use BigInt or widen your numeric path when k or the digits are large enough to exceed safe integers.
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
Single isArmstrong(n) (two digit passes, k = O(log n)) | O(log n) | O(1) |
intPow(d, k) per digit (naive multiply loop) | O(k) per call | O(1) |
All n in [1, U] with naive intPow | roughly O(U · log² U) | O(1) |
Same range with a fixed table for 0..9 to the power k | O(U log U) digit work | O(1) table |
Auxiliary memory beyond the call stack is a handful of locals in both sample scripts.
Summary
- Definition: sum of each decimal digit raised to the digit-count power equals
n. - Implementation: count digits, accumulate integer powers, compare to the original
n; guardn ≤ 0if required. - Watch-outs: avoid
Math.powrounding for strict equality, watch precision on the sum for hugen, and keep the original value for the final comparison.
Besides the trivial one-digit cases 1–9, the only three-digit Armstrong numbers are 153, 370, 371, and 407. For example, 1³ + 5³ + 3³ = 153.
9 people found this page helpful
