Function to return prime numbers

ⅰ亾dé卋堺 提交于 2019-12-20 03:52:48

问题


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) 

回答1:


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



回答2:


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).



来源:https://stackoverflow.com/questions/28917006/function-to-return-prime-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!