Armstrong Number in JavaScript
A positive number is called an Armstrong number if it is equal to the sum of the cubes of its digits, for example, 0, 1, 153, 370, 371, 407, etc.
In other words, the following equation will be verified
xy..z = xn + yn + ….. + zn
n is the number of digits
For example, 370 is a 3-digit Armstrong number
370 = 33 + 73 + 03
= 27 + 343 + 0
= 370
Now we will see Armstrong’s implementation in Javascript.
Program to check if the given number is an Armstrong number
<!doctype html>
<html>
<head>
<script>
function armstrong()
{
var num = Number(document.getElementById("myInput").value);
let sum = 0;
//store the number to check later
let tmp = num;
//Extract each digit from the number
while(num > 0){
//retrieve the last digit
let d = parseInt(num % 10);
//find the cube
d = d ** 3;
sum = sum + d;
//convert float to Integer
num = parseInt(num / 10);
}
if(tmp === sum)
{
alert("Armstrong number");
}
else
{
alert("Not an armstrong number");
}
}
</script>
</head>
<body>
Enter a number: <input id="myInput">
<button onclick="armstrong()">Check</button>
</body>
</html>
| Result |
|---|
| Enter a number: |




