algorithm - Generate a list of primes up to a certain number -
i'm trying generate list of primes below 1 billion. i'm trying this, kind of structure pretty shitty. suggestions?
a <- 1:1000000000 d <- 0 b <- (i in a) {for (j in 1:i) {if (i %% j !=0) {d <- c(d,i)}}}
this implementation of sieve of eratosthenes algorithm in r.
sieve <- function(n) { n <- as.integer(n) if(n > 1e6) stop("n 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)
Comments
Post a Comment