Construct a DFA over {0,1}* where the string when converted to binary must be divisible by 2 or 3. Also, the number of 1s in the string must not be divisible by
Asked
Active
Viewed 408 times
1 Answers
1
Let the states be (a, b) where a is in {0,1,2,3,4,5} and b is either 0 or 1. a will record the input number mod 6, and b the parity of 1s in the input. The starting state is (0, 0) and the accepting states will be (0, 1), (2, 1), (3, 1), (4, 1) -- that is, it's divisible by 2 or 3 (ie: it's 0, 2, 3 or 4 mod 6), and has an odd number of 1s.
Then transitions are:
- (a, b) -0-> (2a mod 6, b)
- (a, b) -1-> (2a+1 mod 6, 1-b)
This is a picture of the state machine (circle is initial state, double octagon is an accepting state).
The state machine diagram is generated in dot format using this python program:
def state(a, b):
return 'q%d%d' % (a, b)
print('digraph g {')
print(' node [shape=plaintext];')
print(' %s [shape=circle]' % state(0, 0))
for i in (0, 2, 3, 4):
print(' %s [shape=doubleoctagon]' % state(i, 1))
for a in range(6):
for b in range(2):
for x in range(2):
s0 = state(a, b)
s1 = state((2*a+x) % 6, (b+x) % 2)
print(' %s -> %s [label=%s]' % (s0, s1, str(x)))
print('}')
And then run the output through the dot command. On linux that can be something like this: python fsm.py > g.dot && dot g.dot -Tpng -o g.png
(assuming the above code is saved as fsm.py).

Progman
- 16,827
- 6
- 33
- 48

Paul Hankin
- 54,811
- 11
- 92
- 118
-
The state machine is (I believe) minimal. I've added code that generates a picture of the state machine and the picture it outputs with this command line on linux: `python fsm.py > g.dot && dot g.dot -Tpng -o g.png` – Paul Hankin Feb 21 '21 at 09:14
-
1I get the approach, but I believe you're solving the wrong problem. The question wants divisible by 2 OR 3, not 2 AND 3. So you should track just evenness, divisibility by three (not 6) and parity, i.e., 12 states, no? – Petr Skocik Feb 21 '21 at 09:20
-
1@PSkocik yes, you're right - I misread. The problem can be fixed by having (0, 1), (2, 1), (3, 1), (4, 1) accepting since divisible by 2 or 3 means equal to 0, 2, 3, or 4 mod 6. I have subsequently fixed the answer. – Paul Hankin Feb 21 '21 at 09:23
-
1The problem that PSkocik observed has been fixed, so I think the DFA is correct. Whether or not you believe it's correct is up to you :) – Paul Hankin Feb 21 '21 at 09:57
-
@PaulHankin could you check out this other question too? https://stackoverflow.com/questions/66301231/construct-a-dfa-given-the-following – MR.CODER1111 Feb 22 '21 at 06:22