How to find all the numbers that are equal to the sum of the factorials of their digits in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module DigitFactorialModule

    ' Example: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145

    ' Function to compute the factorial of a number
    Function Factorial(n As Integer) As Integer
        Dim fact As Integer = 1

        For i As Integer = 2 To n
            fact *= i
        Next

        Return fact
    End Function

    ' Function to find all numbers equal to the sum of the factorials of their digits
    Sub FindDigitFactorialNumbers()
        ' Precompute factorials of digits 0-9
        Dim factorials As New List(Of Integer)(10)
        For i As Integer = 0 To 9
            factorials.Add(Factorial(i))
        Next

        ' Define an upper limit (7 * 9! is a safe limit for this problem)
        Dim upperLimit As Integer = 7 * factorials(9)

        ' Iterate through all numbers and check the condition
        For num As Integer = 10 To upperLimit
            Dim sum As Integer = 0
            Dim temp As Integer = num

            ' Calculate the sum of factorials of digits
            While temp > 0
                Dim digit As Integer = temp Mod 10
                sum += factorials(digit)
                temp \= 10
            End While

            ' Check if the number equals the sum of the factorials of its digits
            If sum = num Then
                Console.WriteLine($"{num} is a digit factorial number.")
            End If
        Next
    End Sub

    Sub Main()
        FindDigitFactorialNumbers()
    End Sub

End Module



' run:
'
' 145 is a digit factorial number.
' 40585 is a digit factorial number.
'

 



answered Nov 9 by avibootz
...