问题
How can I find a grammar of binary number divisible by 5 with 1 as MSB and find the reversal of L
So, I need a grammar that generates numbers like..
5 = 101
10 = 1010
15 = 1111
20 = 10100
25 = 110011
and so on
回答1:
I'm assuming this is homework and you just want a hint.
Let's consider a somewhat similar question, but in base 10. How can we write a CFG for numbers divisible by 3.
At first glance, this seems unlikely, but it's actually pretty simple. We start with the observation that:
10k ≅ 1 (mod 3)
for any non-negative integer k
.
Now consider an integer dδ
, where d
is a decimal digit and δ
is a (possibly empty) sequence of decimal digits. We write |δ|
for the length of δ
. It's clear that:
d × 10|δ| ≅ d (mod 3)
, since 10|δ| ≅ 1 (mod 3)
.
But dδ = d × 10|δ| + δ
So dδ ≅ d + δ (mod 3)
.
Now suppose we have three languages, L0
, L1
and L2
, where Li
is the language of all decimal numbers which are i mod 3
.
I'm going to abuse notation by writing set inclusion statements as though they were grammatical productions, confusing languages and grammars. Forgive me. It seems easier to read if your focus is on CFGs.
For single digit numbers, we can define:
D0 → 0 | 3 | 6 | 9
D1 → 1 | 4 | 7
D2 → 2 | 5 | 8
and then we have:
L0 → D0
L1 → D1
L2 → D2
By the above arithmetic identities, we also have:
L0 → D0L0 | D1L2 | D2L1
L1 → D0L1 | D1L0 | D2L2
L2 → D0L2 | D1L1 | D2L0
That's a CFG, so we're done. (Well, almost done. It would be useful to prove that L0 ⋃ L1 ⋃ L2
is the set of all strings in the alphabet {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
, but that's easy by induction on the length of the string.)
In fact, not only are Li
context-free languages; they are actually regular languages. So there is a regular expression equivalent to each of them. For example, I believe that L0
is:
(D0|D2D0*D1|(D1|D2D0*D2)(D0|D1D0*D2)*(D2|D1D0*D1))*
Now, how can this be repeated for binary numbers divisible by 5?
回答2:
you can easily come with a grammaer that will give you all the even multiplies of 5 (10,20,30...) now, after you have that one - you can concat the string '101' to it and get almost all the odd multiplies.. you'll
hope this will help - it's probably not the smartest way though
来源:https://stackoverflow.com/questions/24219439/find-a-grammar-of-binary-number-divisible-by-5-with-1-as-msb