How to useArray Reduce() method in Javascript
- Converts the number to a string.
- Uses the
reduce
method on the array of digits to calculate the sum. - Raises each digit to the power of the number of digits.
- Checks if the sum is equal to the original number.
Example: In this example, we are using Array Reduce() method.
Javascript
function isArmstrong(number) { const numStr = number.toString(); const numDigits = numStr.length; const sum = [...numStr].reduce((acc, digit) => acc + Math.pow(parseInt(digit), numDigits), 0); return sum === number; } console.log(isArmstrong(153)); // Example usage |
Output
true
JavaScript Program for Armstrong Numbers
In this article, we will see a JavaScript program to check whether the given number is an Armstrong number or not.
An Armstrong Number is an n-digit number that is the sum of the nth power of its all digits. For instance, Consider a 3-digit number, i.e., 153, which is a 3-digit number, & the sum of the cube of all its digits will be the number itself, i.e. 153.
13 = 1
53 = 5*5*5 = 125
33 = 3*3*3 = 27
13 + 53 + 33 = 1+125+27 = 153
To generalize it to a particular syntax form, then the following syntax will be used:
abcd… = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n)+....
Here a,b,c,d,… denotes the Base number & n denotes the exponent number.
Several methods can be used to check if a number is an Armstrong number or not, which are listed below:
Table of Content
- Using toString() and split() Method
- Using naive Method
- Using Array.from() Method
- Using Array Reduce
Contact Us