in reply to A mod2 Machine.
Thanks for this very thought-provoking write up. It is questioning many of my beliefs and it is good to go back and check on them. For example, The advantage of this mod2 machine is that, there are no mathematical operations, thereby executing faster. is just the opposite of what I would have thought. My background is more C/C++ so before checking the last digit, one has to turn a simple number into something much more complex, a string, and then do some operations on it. I would also have thought that most mathematical operations are in hardware nowadays and should take almost no time. But these assumptions might not be valid in Perl where translating between numbers and strings is build in already.
There is a good article on Wikipedia on divisibility rules: http://en.wikipedia.org/wiki/Divisibility_rule (for the non-mathematicians...).
As for the generalization of your idea, I am a bit sceptical. "Check the last digit" does only work for mod2 and mod5 and not even in all bases. For example, 11 base 3 is an even number (4). 14 base 16 is divisible by 5 (20). Other rules are more complex and also depend on the base. The divisibility rules for 3 and 9 based on the sum of the digits rely on 10**n % 3 = 1 and 10**n % 9 = 1. In base 3 a number is divisible by 3 if the last digit is 0.
Another thing I am wondering is whether the speed-up does rely on providing an outright string into the regex? So how does
"112358" =~ /['0' | '2' | '4' | '6' | '8']$/i ? print "even\n" : prin +t "odd\n";
my $n = 112358; $n =~ /['0' | '2' | '4' | '6' | '8']$/i ? print "even\n" : print "odd +\n";
It would be great if someone familiar with Perl's inner workings could comment on this.