How to find all the numbers that are equal to the sum of the factorials of their digits in TypeScrip

1 Answer

0 votes
// Example: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145

// Function to compute the factorial of a number
function factorial(n: number): number {
  let fact: number = 1;

  for (let i = 2; i <= n; i++) {
    fact *= i;
  }

  return fact;
}

// Function to find all numbers equal to the sum of the factorials of their digits
function findDigitFactorialNumbers(): void {
  // Precompute factorials of digits 0-9
  const factorials: number[] = Array.from({ length: 10 }, (_, i) => factorial(i));

  // Define an upper limit (7 * 9! is a safe limit for this problem)
  const upperLimit: number = 7 * factorials[9];

  // Iterate through all numbers and check the condition
  for (let num = 10; num <= upperLimit; num++) {
    let sum: number = 0;
    let temp: number = num;

    // Calculate the sum of factorials of digits
    while (temp > 0) {
      const digit = temp % 10;
      sum += factorials[digit];
      temp = Math.floor(temp / 10);
    }

    // Check if the number equals the sum of the factorials of its digits
    if (sum === num) {
      console.log(`${num} is a digit factorial number.`);
    }
  }
}

findDigitFactorialNumbers();



/*
run:

"145 is a digit factorial number." 
"40585 is a digit factorial number." 

*/


 



answered 3 days ago by avibootz
...