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

1 Answer

0 votes
program DigitFactorialNumbers;

const
  MaxDigit = 9;

function Factorial(n: Integer): LongInt;
var
  i, fact: LongInt;
begin
  fact := 1;
  for i := 2 to n do
    fact := fact * i;
  Factorial := fact;
end;

procedure FindDigitFactorialNumbers;
var
  factorials: array[0..MaxDigit] of LongInt;
  i, num, temp, digit, sum, upperLimit: LongInt;
begin
  // Precompute factorials of digits 0-9
  for i := 0 to MaxDigit do
    factorials[i] := Factorial(i);

  upperLimit := 7 * factorials[9]; // 7 * 9! is a safe upper bound

  for num := 10 to upperLimit do
  begin
    sum := 0;
    temp := num;

    while temp > 0 do
    begin
      digit := temp mod 10;
      sum := sum + factorials[digit];
      temp := temp div 10;
    end;

    if sum = num then
      writeln(num, ' is a digit factorial number.');
  end;
end;

begin
  FindDigitFactorialNumbers;
end.




(*
run:

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

*)

 



answered Nov 9, 2025 by avibootz
...