Imports System
Imports System.Text.RegularExpressions
Module BinaryDivisibleBy7
' Check if a string contains only "0" and "1"
Function IsBinary(s As String) As Boolean
Static binary As New Regex("^[01]+$")
Return binary.IsMatch(s)
End Function
'
' In decimal: reading "123" means
' remainder = remainder * 10 + digit
'
' In binary: reading "1011" means
' remainder = remainder * 2 + bit
'
'
' 0 (0*2 + 0) % 7 0
' 0 (0*2 + 0) % 7 0
' 0 (0*2 + 0) % 7 0
' 1 (0*2 + 1) % 7 1
' 1 (1*2 + 1) % 7 3
' 1 (3*2 + 1) % 7 0
' 0 (0*2 + 0) % 7 0
' 0 (0*2 + 0) % 7 0
'
' Compute binary string modulo 7 without overflow
Function DivisibleBy7(s As String) As Boolean
Dim remainder As Integer = 0
For Each c As Char In s
remainder = (remainder * 2 + (Convert.ToInt32(c) - Convert.ToInt32(c))) Mod 7
Next
Return remainder = 0
End Function
Sub Main()
Dim s As String = "00011100" ' 28
If Not IsBinary(s) Then
Console.WriteLine("Not a binary string")
Return
End If
If DivisibleBy7(s) Then
Console.WriteLine("Divisible by 7")
Else
Console.WriteLine("Not divisible by 7")
End If
End Sub
End Module
'
' run:
'
' Divisible by 7
'