当前位置: 动力学知识库 > 问答 > 编程问答 >

Prime numbers on r

问题描述:

Hey 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 eg;

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

网友答案:

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))
网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: