[R] Function to find prime numbers

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Oct 13 17:30:12 CEST 2009


On Tue, Oct 13, 2009 at 2:41 PM, Thomas Lumley <tlumley at u.washington.edu> wrote:
> On Tue, 13 Oct 2009, AJ83 wrote:
>
>>
>> I need to create a function to find all the prime numbers in an array. Can
>> anyone point me in the right direction?

 This almost sounds like a homework problem to me... So here's a
solution that you can happily present to a tutor - if you can explain
how it works, then you deserve full marks!

primer=function(v){
  return(regexpr("^1$|^(11+?)\\1+$",unlist(lapply(v,function(z){paste(rep("1",z),sep='',collapse='')})),perl=TRUE)
== -1)
}

Test:

 > (1:30)[primer(1:30)]
 [1]  2  3  5  7 11 13 17 19 23 29

I'm not sure how big a number this works for....

R golf anyone?

Barry




More information about the R-help mailing list