How to find the first power of 2 whose leading digits are 12 in VB.NET

1 Answer

0 votes
Imports System
Imports System.Math

Module LeadingDigits

    ' return true if 2^n starts with prefix, else false
    Function startsWithPrefix(n As Long, prefix As Integer) As Boolean
        Dim log2v As Double = Log10(2.0)

        Dim x As Double = n * log2v
        Dim frac As Double = x - Floor(x)

        ' count digits in prefix
        Dim buf As String = prefix.ToString()
        Dim digits As Integer = buf.Length

        ' compute leading digits
        Dim leading As Integer = CInt(Floor(Pow(10, frac + digits - 1)))

        Return leading = prefix
    End Function

    Sub Main()
        Dim prefix As Integer = 12

        Dim n As Long = 1
        While True
            If startsWithPrefix(n, prefix) Then
                Console.WriteLine("First n = " & n)
                Console.WriteLine("2 ^ " & n & " = " & CInt(Pow(2, n)))
                Exit While
            End If
            n += 1
        End While
    End Sub

End Module



' run:
'
' First n = 60
' 2 ^ 60 = 128
'


 



answered 3 hours ago by avibootz
edited 3 hours ago by avibootz

Related questions

...