How to find the first 3 integers equal to the sum of their digits raised to some power in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module DigitPower

    ' compute sum of digits
    Function digitSum(n As Long) As Long
        Dim s As Long = 0

        While n > 0
            s += n Mod 10
            n \= 10
        End While

        Return s
    End Function

    Sub Main()
        Dim results As New List(Of Long)()

        For n As Long = 2 To Long.MaxValue
            If results.Count >= 3 Then Exit For

            Dim s As Long = digitSum(n)

            ' Try powers k = 2..10 (enough for reasonable ranges)
            Dim p As Long = s * s
            For k As Integer = 2 To 10
                If p = n Then
                    Console.WriteLine("Found: " & n &
                                      " = (" & s & ")^" & k)
                    results.Add(n)
                    Exit For ' stop checking powers for this n
                End If
                p *= s ' next power
            Next
        Next

        Console.WriteLine()
        Console.WriteLine("First 3 numbers:")
        For Each x In results
            Console.WriteLine(x)
        Next
    End Sub

End Module


' run:
'
' Found: 81 = (9)^2
' Found: 512 = (8)^3
' Found: 2401 = (7)^4
'
' First 3 numbers:
' 81
' 512
' 2401
'

 



answered 12 hours ago by avibootz

Related questions

...