How to write 4 different functions that check if a number is a power of 2 in VB.NET

1 Answer

0 votes
Imports System
				
Module PowerOfTwoCheck

    ' Method A: Bit-counting (similar to your Python example)
    Function IsPowerOfTwoA(x As Integer) As Boolean
        If x <= 0 Then Return False
        Return System.Numerics.BitOperations.PopCount(CUInt(x)) = 1
    End Function

    ' Method B: Bitwise trick
    Function IsPowerOfTwoB(x As Integer) As Boolean
        Return x > 0 AndAlso (x And (x - 1)) = 0
    End Function

    ' Method C: Repeated division
    Function IsPowerOfTwoC(x As Integer) As Boolean
        If x <= 0 Then Return False
        While x Mod 2 = 0
            x \= 2
        End While
        Return x = 1
    End Function

    ' Method D: Using logarithms
    Function IsPowerOfTwoD(x As Integer) As Boolean
        If x <= 0 Then Return False
        Dim logVal As Double = Math.Log(x) / Math.Log(2)
        Return Math.Abs(logVal - Math.Round(logVal)) < 1.0E-10
    End Function

    Sub Main()
        Dim test1 As Integer = 16   ' true
        Dim test2 As Integer = 18   ' false

        Console.WriteLine("A: " & IsPowerOfTwoA(test1) & ", " & IsPowerOfTwoA(test2))
        Console.WriteLine("B: " & IsPowerOfTwoB(test1) & ", " & IsPowerOfTwoB(test2))
        Console.WriteLine("C: " & IsPowerOfTwoC(test1) & ", " & IsPowerOfTwoC(test2))
        Console.WriteLine("D: " & IsPowerOfTwoD(test1) & ", " & IsPowerOfTwoD(test2))
    End Sub

End Module



' OUTPUT:
'
' A: True, False
' B: True, False
' C: True, False
' D: True, False
'

 



answered Apr 2 by avibootz

Related questions

...