// Example: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145
object DigitFactorialApp {
// Function to compute the factorial of a number
def factorial(n: Int): Int = {
(2 to n).product
}
// Function to find all numbers equal to the sum of the factorials of their digits
def findDigitFactorialNumbers(): Unit = {
// Precompute factorials of digits 0-9
val factorials: Vector[Int] = (0 to 9).map(factorial).toVector
// Define an upper limit (7 * 9! is a safe limit for this problem)
val upperLimit: Int = 7 * factorials(9)
// Iterate through all numbers and check the condition
for (num <- 10 to upperLimit) {
var sum = 0
var temp = num
// Calculate the sum of factorials of digits
while (temp > 0) {
val digit = temp % 10
sum += factorials(digit)
temp /= 10
}
// Check if the number equals the sum of the factorials of its digits
if (sum == num) {
println(s"$num is a digit factorial number.")
}
}
}
def main(args: Array[String]): Unit = {
findDigitFactorialNumbers()
}
}
/*
run:
145 is a digit factorial number.
40585 is a digit factorial number.
*/