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*