JavaScript Program to Display Armstrong Number Between Two Intervals
An Armstrong number is a number that is 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. In this article, we’ll explore how to create a JavaScript program to display all Armstrong numbers within a given range.
To find Armstrong numbers between two intervals, we need to:
- Iterate through all numbers in the given range.
- For each number, determine the number of digits (n).
- Calculate the sum of each digit raised to the power of n.
- Check if the calculated sum is equal to the original number. If it is, the number is an Armstrong number.
Basic Approach
Here’s a simple implementation to find and display Armstrong numbers between two given intervals:
Javascript
function isArmstrongNumber(num) { let sum = 0; let temp = num; const numberOfDigits = num.toString().length; while (temp > 0) { let digit = temp % 10; sum += Math.pow(digit, numberOfDigits); temp = Math.floor(temp / 10); } return sum === num; } function displayArmstrongNumbers(start, end) { for (let i = start; i <= end; i++) { if (isArmstrongNumber(i)) { console.log(i); } } } displayArmstrongNumbers(100, 1000); |
153 370 371 407
Using Array Methods
Alternatively, you can use JavaScript array methods to make the code more concise:
Javascript
function isArmstrongNumber(num) { return num.toString() .split( '' ) .map(Number) .reduce((sum, digit, _, {length}) => sum + Math.pow(digit, length), 0) === num; } function displayArmstrongNumbers(start, end) { for (let i = start; i <= end; i++) { if (isArmstrongNumber(i)) { console.log(i); } } } displayArmstrongNumbers(100, 1000); |
153 370 371 407
The split() method is used to convert the number to an array of digits, map(Number) converts each digit back to a number, and reduce() calculates the sum of each digit raised to the power of the number of digits.