An Armstrong number equals the sum of its digits, each raised to the power of the number of digits (e.g. \(153 = 1^3 + 5^3 + 3^3\)). The script below reads a number from the user and checks this.
<!DOCTYPE html>
<html>
<body>
<input type="number" id="num" placeholder="Enter a number">
<button onclick="checkArmstrong()">Check</button>
<p id="result"></p>
<script>
function checkArmstrong() {
let str = document.getElementById("num").value;
let n = parseInt(str);
if (isNaN(n) || n < 0) {
document.getElementById("result").innerHTML = "Enter a valid number";
return;
}
let digits = String(n).length;
let sum = 0, temp = n;
while (temp > 0) {
let d = temp % 10;
sum += Math.pow(d, digits);
temp = Math.floor(temp / 10);
}
let msg = (sum === n) ? n + " is an Armstrong number"
: n + " is not an Armstrong number";
document.getElementById("result").innerHTML = msg;
}
</script>
</body>
</html>
How it works
- The value typed in the input box is read and converted to an integer.
digits stores the number of digits (3 for 153).
- The loop takes the last digit with
% 10, adds its power to sum, and removes it with Math.floor(temp / 10).
- If
sum equals the original number, it is an Armstrong number.
Test: 153 → \(1 + 125 + 27 = 153\) (Armstrong); 370, 371, 407 and 9474 are also Armstrong numbers; 123 → \(1 + 8 + 27 = 36\) (not). A simpler version can use let n = parseInt(prompt("Enter a number")); and alert(msg).