Search code examples
algorithmrprimes

Generate a list of primes up to a certain number


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)}}}

Solution

  • 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
       last.prime <- 2L
       for(i in last.prime:floor(sqrt(n)))
       {
          primes[seq.int(2L*last.prime, n, last.prime)] <- FALSE
          last.prime <- last.prime + min(which(primes[(last.prime+1):n]))
       }
       which(primes)
    }
    
     sieve(1000000)