How to find the first integer equal to the sum of its digits raised to some power in VB.NET

1 Answer

0 votes
Imports System

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 n As Long = 2

        While True
            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)
                    Return
                End If
                p *= s ' next power
            Next

            n += 1
        End While
    End Sub

End Module


' run:
'
' Found: 81 = (9)^2
'

 



answered 1 day ago by avibootz

Related questions

...