In this article, we will discuss the JavaScript program to check Armstrong numbers and how it works. An Armstrong number, also known as a selfish number, is a number equal to the sum of its digits each raised to the power of the number of digits. This concept is used in various computer programs, including JavaScript, to determine whether or not a given number is an Armstrong number.
What is an Armstrong Number?
An Armstrong number is a number equal to the sum of its digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. This concept can be applied to any number, regardless of size, as long as it has a positive integer value.
How Does the JavaScript Program to Check Armstrong Number Work?
The JavaScript program to check Armstrong number works by using a series of steps to determine whether a given number is an Armstrong number. The first step is to convert the given number into a string and then find the length of the string. This length represents the number of digits in the given number.
Next, the program will use a for loop to iterate over each digit in the given number and raise it to the power of the number of digits. The result of each iteration is then added to a running total.
Finally, the program compares the running total to the original number. If they are equal, the given number is an Armstrong number, and the program returns true. If they are not equal, the given number is not an Armstrong number, and the program returns false.
Example of a JavaScript Program to Check Armstrong Number
function isArmstrongNumber(num) {
let strNum = num.toString();
let length = strNum.length;
let result = 0;
for (let i = 0; i < length; i++) {
let digit = parseInt(strNum.charAt(i));
result += Math.pow(digit, length);
}
return result === num;
}
console.log(isArmstrongNumber(153)); // true
console.log(isArmstrongNumber(370)); // true
console.log(isArmstrongNumber(371)); // true
console.log(isArmstrongNumber(407)); // true
console.log(isArmstrongNumber(1634)); // true
console.log(isArmstrongNumber(8208)); // true
console.log(isArmstrongNumber(9474)); // true
In this example, the isArmstrongNumber
function takes a single parameter num
, which is the number we want to check if it is an Armstrong number. The function starts by converting the number into a string and finding its length. This length is then used to calculate the power that each digit will be raised to.
The program then uses a for loop to iterate over each digit in the given number and raise it to the power of the number of digits. The result of each iteration is then added to a running total.
Finally, the program compares the running total to the original number. If they are equal, the given number is an Armstrong number, and the program returns true. If they are not equal, the given number is not an Armstrong number, and the program returns false.
Thanks for reading. Happy coding!