Imports System
Imports System.Text
Class PowerOfTwoDigitSum
Public Shared Function Calculate2PowerNAsString(ByVal N As Integer) As String
' Calculate 2^N as a string for large numbers
Dim result As New StringBuilder("1")
For i As Integer = 1 To N
Dim carry As Integer = 0
For j As Integer = 0 To result.Length - 1
Dim digit As Integer = Convert.ToInt32(result(j)) - Convert.ToInt32("0"c)
Dim num As Integer = digit * 2 + carry
result(j) = Convert.ToChar((num Mod 10) + Convert.ToInt32("0"c))
carry = num \ 10
Next
While carry > 0
result.Append(Convert.ToChar((carry Mod 10) + Convert.ToInt32("0"c)))
carry \= 10
End While
Next
Return result.ToString()
End Function
Public Shared Function SumOfDigits(ByVal N As Integer) As Integer
Dim result As String = Calculate2PowerNAsString(N)
Dim sum As Integer = 0
For Each digit As Char In result
sum += Convert.ToInt32(digit) - Convert.ToInt32("0"c)
Next
Return sum
End Function
Public Shared Sub Main()
Dim N As Integer = 15
Console.WriteLine("Sum of digits of 2^{0} is: {1}", N, SumOfDigits(N))
N = 100
Console.WriteLine("Sum of digits of 2^{0} is: {1}", N, SumOfDigits(N))
N = 1000
Console.WriteLine("Sum of digits of 2^{0} is: {1}", N, SumOfDigits(N))
End Sub
End Class
' run:
'
' Sum of digits of 2^15 is: 26
' Sum of digits of 2^100 is: 115
' Sum of digits of 2^1000 is: 1366
'