Keep It Simple, Stupid | |
PerlMonks |
Re: is it prime?by tobyink (Canon) |
on May 06, 2012 at 06:19 UTC ( [id://969117]=note: print w/replies, xml ) | Need Help?? |
As JavaFan said, the simplest solution is to just start your loop at 2:
The above does however produce a false negative for isPrime(2). It produces a negative for isPrime(1) which is probably correct, but could be considered to be a false depending on your stance on the much debated primality of 1. Better though is:
I've folded in JavaFan's other suggestions, plus changed your prototype from ($) to (_). Prototypes are rarely helpful - you're best off leaving them out usually. In this case though, the (_) prototype is quite cool, because what it does is, if isPrime is called with no argument at all, then it checks $_. Other suggestions: consider what should happen for isPrime(1), isPrime(0), isPrime(-3) and isPrime("chimpanzee"). Add checks for those special cases before the for my $div loop. The above implementation claims all the above are prime, except -3 which dies. In mathematical circles, 1 is (these days) not usually regarded as prime, and asking the question of non-natural numbers (i.e. non-integers, and integers lower than 1) does not make sense. Bearing that in mind...
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
In Section
Seekers of Perl Wisdom
|
|