user446667 user446667 - 1 year ago 88
R Question

Generate a list of primes in R up to a certain number

Hey, I'm trying to generate a list of primes below 1 billion. I'm trying this, but this kind of structure is pretty shitty. Any suggestions?

a <- 1:1000000000
d<- 0
b <- for (i in a) {for (j in 1:i) {if (i %% j !=0) {d <- c(d,i)}}}

Answer Source

This is an implementation of the Sieve of Eratosthenes algorithm in R.

sieve <- function(n)
   n <- as.integer(n)
   if(n > 1e6) stop("n too large")
   primes <- rep(TRUE, n)
   primes[1] <- FALSE <- 2L
   for(i in
      primes[*, n,] <- FALSE <- + min(which(primes[(]))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download