Prime Number Generator in R

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] <- n[which(n %% p==0)] <-[! %in% p]
    n <- n[! n %in%]
    i <- i + 1

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

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!


2 thoughts on “Prime Number Generator in R

  1. Rusty says:

    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.

    • Mike Silva says:

      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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s