I am self-studying regular expressions and found an interesting practice problem online that involves writing a regular expression to recognize all binary numbers divisible by 3
The problem you're encountering is that whilst your trick is (probably) valid, it doesn't map to a practical DFA (you have to track a potentially arbitrary difference between the number of even and odd ones, which would require an arbitrary number of states).
An alternative approach is to note that (working from MSB to LSB) after the i
-th character , x[i]
, your substring must either be equal to 0, 1, or 2 in modulo-3 arithmetic; call this value S[i]
. x[i+1]
must be either 0 or 1, which is equivalent to multiplying by 2 and optionally adding 1.
So if you know S[i]
and x[i+1]
, you can calculate S[i+1]
. Does that description sound familiar?