Unlock the Secrets of Armstrong Numbers
What is an Armstrong Number?
An Armstrong number, also known as a narcissistic number, is a positive integer that satisfies a specific condition. When the sum of its digits, each raised to the power of the number of digits, equals the original number itself, it’s considered an Armstrong number. For instance, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153
.
JavaScript Program to Check Armstrong Numbers
Before we begin, make sure you have a solid grasp of JavaScript fundamentals, including for loops, while and do…while loops. Now, let’s create a program to find Armstrong numbers between two intervals.
function findArmstrongNumbers() {
const lowerBound = parseInt(prompt("Enter the lower bound: "));
const upperBound = parseInt(prompt("Enter the upper bound: "));
for (let i = lowerBound; i <= upperBound; i++) {
const numStr = i.toString();
const numDigits = numStr.length;
let sum = 0;
let temp = i;
while (temp > 0) {
const digit = temp % 10;
sum += Math.pow(digit, numDigits);
temp = Math.floor(temp / 10);
}
if (sum === i) {
console.log(i + " is an Armstrong number.");
}
}
}
findArmstrongNumbers();
The Program Explained
Our program prompts the user to input two integers, which serve as the lower and upper bounds for our search. We use the parseInt()
function to convert these inputs into integer values. Next, we employ a for
loop to iterate through the range of numbers defined by the user.
Converting Numbers to Strings
To extract each digit from the number, we utilize the toString()
method, which converts the number to a string. The length
property then gives us the total number of digits in the number.
The Magic of Modulus
Within our loop, we use a while
loop to iterate the number, extracting each digit using the modulus operator %
. By dividing the number by 10, we obtain the remainder, which represents the last digit. We then multiply this remainder by the number of digits in the number and calculate the sum.
Removing Digits and Calculating the Sum
To remove the last digit, we divide the number by 10. This process continues until we’ve processed all digits. Finally, we compare the calculated sum with the original number entered by the user. If they match, we’ve found an Armstrong number!
The Loop Continues
Our program repeats this process for all numbers within the specified range, providing a comprehensive list of Armstrong numbers between the lower and upper bounds defined by the user.
Now, it’s your turn to try! Run the program and explore the fascinating world of Armstrong numbers. Who knows what secrets you’ll uncover?