[R] Function to find prime numbers

joris meys jorismeys at gmail.com
Wed Oct 14 00:18:57 CEST 2009


On Tue, Oct 13, 2009 at 5:30 PM, Barry Rowlingson
<b.rowlingson at lancaster.ac.uk> wrote:
> 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!

This almost sounds like an extra assignment to me :-)

>
> 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?

I take the challenge and give AJ some more stuff to think about.

First the obvious :

primer=function(v){
 return(regexpr("^1$|^(11+?)\\1+$",sapply(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

Shorter, if I keep the same use of the function primer :

primer=function(v){
 return(sapply(v,function(z){sum(z/1:z==z%/%1:z)})==2)
}
(1:30)[primer(1:30)]
 [1]  2  3  5  7 11 13 17 19 23 29

nchar("primer=function(v){  . . .  (1:30)[primer(1:30)]")
[1] 97


This works for all numbers. It also allows for a function primes :

primes=function(v){
	return(v[sapply(v,function(z){sum(z/1:z==z%/%1:z)==2})])
}
primes(1:30)
 [1]  2  3  5  7 11 13 17 19 23 29

> nchar("primes=function(v){  . . .  primes(1:30)")
[1] 91

Cheers
Joris




More information about the R-help mailing list