Horje
JavaScript Program to Display Armstrong Numbers Between 1 to 1000

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



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Display Data Values on Chart.js ? How to Display Data Values on Chart.js ?
JavaScript Program to Check whether the Input Number is a Neon Number JavaScript Program to Check whether the Input Number is a Neon Number
$ in JavaScript $ in JavaScript
How to Sort Objects in an Array Based on a Property in a Specific Order in TypeScript ? How to Sort Objects in an Array Based on a Property in a Specific Order in TypeScript ?
How to Define Generic Type for Matching Object Property Types in TypeScript ? How to Define Generic Type for Matching Object Property Types in TypeScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16