I recently needed to generate a small number of prime numbers. I wrote this little function that uses the sieve of Eratosthenes.

prime.numbers <- function(limit){
n <- 2:limit
i <- 1
while(i < length(n)){
p <- n[i]
not.prime <- n[which(n %% p==0)]
not.prime <- not.prime[! not.prime %in% p]
n <- n[! n %in% not.prime]
i <- i + 1
}
n
}

So if you wanted all prime numbers from 1 to 100 you would do the following:

prime.numbers(100)
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

It is not the most efficient algorithm but it served me well. Hope it helps you too!

### Like this:

Like Loading...

*Related*

This just might be the worst prime generator I’ve encountered, and it bears no relation to the Sieve of Eratosthenes. The author has severely lacking R skills, coupled with no understanding of time complexity whatsoever.

Rusty – Thank you for your comments. You are correct that bears no relation to the Sieve of Eratosthenes. I must have read the article and it inspired me on an approach to the problem. I would love to see an example of a prime generator that does. As to your comments on time complexity it is admittedly not an efficient way but was sufficient for the task I was trying to tackle. If you have a better way please share. Thanks.