isPrime in One Line of Perl
As a follow up to Finding the first 20 terms in the Fibonacci Series, next in the 3Monkey Golf series — Determining if a number is prime. The following is a fairly simple Perl one liner to do the trick. I’m interested in seeing implementations in other languages. I will be posting follow ups with the best submissions from both Golf challenges at the end of the week.
Perl Code
perl -wle'print(1)if(1xtarget_number)!~/^1?$|^(11+?)\1+$/'
Character count = 36
Golf Rules:
Please note that use og characters such as > and < require escaping as & lt; and & gt;
If you have difficulty posting your solution please email me the solution at stacy (at) 3monkeyweb (period) com and I will make sure it gets posted.
Good luck, and until next time.
-3Monkeys
Popularity: 35% [?]

















July 17th, 2007 at 8:32 am
The quote at the end of your one line is the wrong type, copy-pasting it doesn’t work (it’s early and it took me a while to spot that)
And for people who want to see how and why this works, have a look here:
http://montreal.pm.org/tech/neil_kandalgaonkar.shtml
July 17th, 2007 at 3:19 pm
Finally got the ' correct
It should work now as a copy/paste.
July 17th, 2007 at 5:20 pm
@Bloid, I think that’s where I first found this one. I have several of these tucked away for study.
July 17th, 2007 at 7:27 pm
Unfortunately, the code doesn’t work: perl -wle ‘print(1)if(1x(2E+32582657-1))!~/^1?$|^(11+?)\1+$/’ outs nothing. But 2E+32582657-1 IS prime. In fact it’s the largest prime ever found. Well, 2E+32582657-1 is “inf” in Perl, but it’s a fault of Perl, not us fellow programmers. Perl is just not suitable for this kind of tasks. Or prove us it is. Anyway, the idea and syntax are very, very cool. *bows*
July 17th, 2007 at 7:52 pm
@Mikhail, that is why I added the “should be able to be replaced with any reasonable number” caveat in the “rules”. You are correct though about perl being able to handle extremely large numbers. I was hoping for a python shot at it as it should be able to handle it.
July 18th, 2007 at 6:18 am
Well, I see. The same “functionality” Python code is: not re.match(’^1?$|^(11+?)\\1+$’,'1′*target_number) and is 38 chars. Prints “True” if the target_number is prime. However, it doesnt work with long integers and string integers. Definitely good way is to use SciPy library.
July 18th, 2007 at 5:59 pm
http://www.dzone.com/links/isprime_in_one_line_of_groovy.html