Open In App

JavaScript Program to Display Armstrong Numbers Between 1 to 1000

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Armstrong number is a number equal to the sum of its digits raised to the power 3 of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. This article will explore how to find Armstrong numbers between 1 to 1000 using JavaScript.

Approach 1: Display Armstrong Numbers Between 1 to 1000 using a Loop

The simplest approach to finding Armstrong numbers is using a loop to iterate through each number from 1 to 1000 and check if it is an Armstrong number.

Javascript




function isArmstrong(number) {
    let sum = 0;
    let temp = number;
    const digitsCount = number.toString().length;
  
    while (temp > 0) {
        let digit = temp % 10;
        sum += Math.pow(digit, digitsCount);
        temp = Math.floor(temp / 10);
    }
  
    return sum === number;
}
  
// Driver code
let N = 1000;
  
for (let i = 1; i <= N; i++) {
    if (isArmstrong(i)) {
        console.log(i);
    }
}


Output

1
2
3
4
5
6
7
8
9
153
370
371
407

Approach 2: Display Armstrong Numbers Between 1 to 1000 using Array Methods

We can also use JavaScript array methods to make the code more concise and functional. In this approach, we convert the number to a string, split it into an array of digits, and then use the reduce method to calculate the sum of each digit raised to the power of the number of digits.

Javascript




function isArmstrong(number) {
    return number === number
        .toString()
        .split('')
        .reduce((sum, digit, _, { length }) => sum + Math.pow(digit, length), 0);
}
  
// Driver code
N = 1000;
  
for (let i = 1; i <= N; i++) {
    if (isArmstrong(i)) {
        console.log(i);
    }
}


Output

1
2
3
4
5
6
7
8
9
153
370
371
407


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads