How to use Array reduce() method In Javascript
In this approach, we are using the reduce() method to iteratively calculate the sum of factorials for each digit of the given number by converting it to an array of digits, applying the factorial function (fact), and accumulating the results. The final comparison determines whether the sum equals the original number, which prints the output in a ‘Yes‘ or ‘No‘ format.
Syntax:
array.reduce(callback, initialValue);
Example: The below example uses the reduce() function to Check Whether a Number is a Strong Number in JavaScript.
let fact = (num) => (num <= 1 ? 1 :
num * fact(num - 1));
let res = (n) => {
let sum = n
.toString()
.split('')
.reduce((acc, digit) => acc +
fact(Number(digit)), 0);
return sum === n ? 'Yes' : 'No';
};
console.log(res(145));
console.log(res(534));
Output
Yes No
Check Whether a Number is Strong Number in JavaScript
Strong Numbers are the numbers whose sum of the factorial of digits is equal to the original number. In JavaScript, we can check whether the number is a strong number or not using various approaches. In this article, we will explore all the possible approaches with their practical implementation.
These are the following methods:
Table of Content
- Using Array reduce() method
- Using for…of Loop
- Using while Loop