开发者

Regular expressions and divisibility

开发者 https://www.devze.com 2023-03-27 08:33 出处:网络
How can I create a regular expression which test if a number is divisible by i (2<=i<=10), 8 expressions in total? One can only assume that integers are positive. You can 开发者_StackOverflow社区

How can I create a regular expression which test if a number is divisible by i (2<=i<=10), 8 expressions in total? One can only assume that integers are positive. You can 开发者_StackOverflow社区use symbols [] and [^] , ?, * and + , | and (). PHP's ereg-function should accept it.


Unless this is a homework problem there is no reason to use regular expressions in this case.

Use the modulus operator, it gives you the remainder 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 it's an interview question. Yes, the correct answer here is "That is not the correct tool for this problem!"


@Charles answer in his comment is incorrect. Here is how you build a regex for divisbility by 3: http://alokmenghrajani.github.com/triple/. You can do something similar for 7.


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

Then you can check whether your number matches ^(1{divisor})*$. If you can't use {}, you need to spell it out. So to check divisibility by 4, try to match ^(1111)*$, etc.

Nobody in their right mind would do it that way, though. And if your interviewer asks you to use ereg, then his regex knowledge is a few decades old, I guess.


So, obviously you wouldn't use a regular expression for this normally... but people do crazy things. There's a regular expression out there to determine if a number is prime...

As a thought on how to go about a solution, if you're allowed to represent the number in another format...

  • Convert the number to a string with a number of 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 can't use the {} construct, you can replace the 1{$i} with a number of ones equal to i.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号