1

I want to write a function in R which accepts a list of integers and returns only the values which are prime.

So far I have this:

 primefindlist<-function(n){
 return(n[n==2 | all(n %% seq(2,ceiling(sqrt(n)),by=1) !=0)])
 }

But I keep getting an error message when I run the function e.g;

 primefindlist(c(7,11))

Error in seq.default(2, ceiling(sqrt(n)), by = 1) : 'to' must be of length 1

Anyone got any ideas how to overcome this?

Also the code below tells me if a single integer is prime or not ie is.prime(7) outputs TRUE

is.prime <- function(n) n == 2L || all(n %% 2L:ceiling(sqrt(n)) != 0) 
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Namch96
  • 187
  • 6

2 Answers2

3

The function is not vectorized. Try

primefindlist<-function(x){
  return(x[x==2 | sapply(x, function(n)all(n %% seq(2,ceiling(sqrt(n)),by=1) !=0))])
}

or

primefindlist<-function(n){
  return(n[n==2 | all(n %% seq(2,ceiling(sqrt(n)),by=1) !=0)])
}
vPrimefindlist <- Vectorize(primefindlist, vectorize.args = "n")
vPrimefindlist(c(7,11))
lukeA
  • 53,097
  • 5
  • 97
  • 100
  • Hey Luke, you know in your first answer above if there a way of not writing function(n)all(n %% seq(2,ceiling(sqrt(n)),by=1) !=0 and instead calling that function a name and using the name in the sapply part ? – Namch96 Mar 07 '15 at 17:23
  • 1
    Sure. `primefindlist<-function(x){ f <- function(n)all(n %% seq(2,ceiling(sqrt(n)),by=1) !=0); return(x[x==2 | sapply(x, f)]) }` should work, too. – lukeA Mar 07 '15 at 19:40
1

How about using isprime from the gmp library?

myPrimes <- function(x) {x[which(isprime(x)>0)]}

Here are some tests:

set.seed(33)
randSamp <- sample(10^6,10^5)

system.time(t1 <- myPrimes(randSamp))
user  system elapsed 
0.07    0.00    0.08 

system.time(t2 <- primefindlist(randSamp))
user  system elapsed 
7.04    0.00    7.06 

all(t1==t2)
[1] TRUE

If you are interested, the isprime function implements the Miller-Rabin primality test. It is fairly easy to write this algorithm yourself if you are determined to not use any external libraries. Rosetta Code is a good place to start (there currently isn't an R implementation yet).

Joseph Wood
  • 7,077
  • 2
  • 30
  • 65