JavaScript Program to Check Armstrong Number
function isArmstrong(num) { const digits = num.toString().length; let sum = 0; let temp = num; while (temp > 0) { let digit = temp % 10; sum += digit ** digits; temp = Math.floor(temp / 10); } return sum === num; }.Examples
How to Think About It
Algorithm
Code
function isArmstrong(num) { const digits = num.toString().length; let sum = 0; let temp = num; while (temp > 0) { let digit = temp % 10; sum += digit ** digits; temp = Math.floor(temp / 10); } return sum === num; } console.log(isArmstrong(153)); console.log(isArmstrong(9474)); console.log(isArmstrong(123));
Dry Run
Let's trace the number 153 through the code
Count digits
153 has 3 digits
Initialize sum
sum = 0, temp = 153
Extract digit and add power
digit = 153 % 10 = 3; sum = 0 + 3^3 = 27; temp = 15
Next digit
digit = 15 % 10 = 5; sum = 27 + 5^3 = 27 + 125 = 152; temp = 1
Next digit
digit = 1 % 10 = 1; sum = 152 + 1^3 = 152 + 1 = 153; temp = 0
Compare sum and number
sum = 153 equals original number 153, return true
| temp | digit | sum |
|---|---|---|
| 153 | 3 | 27 |
| 15 | 5 | 152 |
| 1 | 1 | 153 |
Why This Works
Step 1: Count digits
We find the number of digits because each digit must be raised to this power.
Step 2: Sum of powers
Each digit is raised to the power of the digit count and added to a sum.
Step 3: Compare sum
If the sum equals the original number, it confirms the number is Armstrong.
Alternative Approaches
function isArmstrong(num) { const digits = num.toString().length; const sum = num.toString().split('').reduce((acc, d) => acc + Number(d) ** digits, 0); return sum === num; } console.log(isArmstrong(153));
function powerSum(num, digits) { if (num === 0) return 0; return (num % 10) ** digits + powerSum(Math.floor(num / 10), digits); } function isArmstrong(num) { const digits = num.toString().length; return powerSum(num, digits) === num; } console.log(isArmstrong(153));
Complexity: O(d) time, O(1) space
Time Complexity
The program loops through each digit once, so time grows linearly with the number of digits, O(d).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The iterative approach is generally fastest and simplest, while recursive and array methods may add overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(d) | O(1) | Simplicity and performance |
| Array reduce | O(d) | O(d) | Concise code, functional style |
| Recursive | O(d) | O(d) | Elegant but uses call stack |