Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for Binary Numbers Divisible by 5

I want to write a regular expression for Binary Numbers Divisible by 5.
I have already done the regular expressions for Binary Numbers Divisible by 2 and for 3 but I couldn't find one for 5.

Any suggestions?

like image 458
The Beast Avatar asked Dec 26 '15 23:12

The Beast


People also ask

How do you know if a binary number is divisible by 5?

5 in base 4 is equivalent to 11. Now apply the rule of divisibility by 11 where you add all the digits at odd places and add all the digits at even places and then subtract one from the other. If the result is divisible by 11(which remember is 5), then the binary number is divisible by 5.

How do you make a number divisible by 5?

For a number to be divisible by 5, the only condition is that the digit at the unit place in the number must be either 0 or 5.

How do you know if a binary number is divisible by a binary number?

Efficient Approach: In the binary string, check for the last k bits. If all the last k bits are 0, then the binary number is evenly divisible by 2k else it is not evenly divisible.

What is the answer of divisible by 5?

A number is divisible by 5 if the number's last digit is either 0 or 5. Divisibility by 5 - examples: The numbers 105, 275, 315, 420, 945, 760 can be divided by 5 evenly.


1 Answers

(0|1(10)*(0|11)(01*01|01*00(10)*(0|11))*1)*

Add ^$ to test it with regexp. See it working here.


You can build a DFA and convert it to regular expression. The DFA was already built in another answer. You can read it, it is very well explained.
The general idea is to remove nodes, adding edges. before

Becomes:

after


Using this transformation and the DFA from the answer I linked, here are the steps to get the regular expression:
(EDIT: Note that the labels "Q3" and "Q4" have been mistakenly swapped in the diagram. These states represent the remainder after modulus 5.) step1 step2 step3 step4 step5
like image 62
ndnenkov Avatar answered Oct 06 '22 23:10

ndnenkov