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]
    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!

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s