Open In App

Print Strong Numbers Within a Range using JavaScript

In mathematics, a strong number is a number whose sum of the factorial of its digits is equal to the number itself. The task is to print all strong numbers within a given range in JavaScript.

Example: 145 is a Strong number because:

1: 1
4: 4*3*2*1=24
5: 5*4*3*2*1=120
120+24+1=145

Since the sum is equal to number, 145 is a Strong number.

Iterative Approach

In this approach, we iterate through the range of numbers and for each number, we calculate the sum of the factorials of its digits iteratively. Then, we check if this sum is equal to the original number.

Example: The below code print Strong Numbers Within a Range using Iterative Approach in JavaScript.

function factorial(num) {
    let fact = 1;
    for (let i = 2; i <= num; i++) {
        fact *= i;
    }
    return fact;
}

function sumOfFactorialOfDigits(number) {
    let sum = 0;
    let temp = number;
    while (temp > 0) {
        let digit = temp % 10;
        sum += factorial(digit);
        temp = Math.floor(temp / 10);
    }
    return sum;
}

function printStrongNumbersInRange(start, end) {
    for (let i = start; i <= end; i++) {
        if (sumOfFactorialOfDigits(i) === i) {
            console.log(i);
        }
    }
}

printStrongNumbersInRange(1, 1000);

Output
1
2
145

Recursive Approach

In this approach, we define a recursive function to calculate the sum of the factorials of the digits of a number. Then, we iterate through the range of numbers and for each number, we call this recursive function to check if it is a strong number.

Example: The below code print Strong Numbers Within a Range using Recursive Approach in JavaScript.

function factorial(num) {
    if (num === 0 || num === 1) {
        return 1;
    } else {
        return num * factorial(num - 1);
    }
}

function sumOfFactorialOfDigits(number) {
    if (number === 0) {
        return 0;
    } else {
        let digit = number % 10;
        return factorial(digit) 
        + sumOfFactorialOfDigits(Math.floor(number / 10));
    }
}

function isStrongNumber(number) {
    return sumOfFactorialOfDigits(number) === number;
}

function printStrongNumbersInRange(start, end) {
    for (let i = start; i <= end; i++) {
        if (isStrongNumber(i)) {
            console.log(i);
        }
    }
}

printStrongNumbersInRange(1, 1000);

Output
1
2
145
Article Tags :