Regular Expressions and Divisibility

How to create a regular expression that checks if a number is divisible by i (2 <= i <= 10), only 8 expressions? One can only assume that the integers are positive. You can use the characters [] and [^],?, * And +, | and(). PHP ereg-function should accept it.

+4
source share
4 answers

If this is not a problem with homework, then there is no reason to use regular expressions.

Use the module operator, it gives you the rest of the value divided by.

if($number%$i) { "This runs if $number modulus is not 0 (not evenly divisible by $i)" } else { "This runs if $number modulus is 0 ( evenly Divisible by $i)" } 

Edit: Oh, this is an interview question. Yes, the correct answer is here: "This is not the right tool for this problem!"

+3
source

@ Reply to comment in his comment is incorrect. Here's how you create a regex for divisbility at 3: http://alokmenghrajani.github.com/triple/ . You can do something similar for 7.

+1
source

This is possible only if you translate the number to unary ( 1 = 1 , 2 = 11 , 3 = 111 , 4 = 1111 , etc.).

Then you can check if your number matches ^(1{divisor})*$ . If you cannot use {} , you need to specify it. So, to check divisibility by 4, try matching ^(1111)*$ , etc.

No one in their right mind would do it that way. And if your interlocutor asks you to use ereg , then his knowledge of regular expressions a few decades ago, I think.

0
source

So obviously, you would not use regex for this normally ... but people are doing crazy things. There is a regex there to determine if a number is prime ...

As a thought on how to solve the problem, if you are allowed to submit the number in a different format ...

  • Convert a number to a string with a number from 1s equal to the size of the number (4 = "1111")
  • regexp /^(1{$divisor})+$/

As a sample in Tcl

 proc testit {value} { set value1 [string repeat 1 $value] for {set i 2} {$i <= 10} {incr i} { set matches [regexp "^(1{$i})+$" $value1] puts "${i}: $matches" } } 

Since you cannot use the {} construct, you can replace 1{$i} with a number equal to i.

0
source

All Articles