R function to find prime numbers

Post date: Jun 26, 2015 4:46:42 PM

# This function returns all prime numbers less than n

# n - input to the function

# Note: 1 is not a prime by definition

is.prime = function(n)

{

n = as.integer(n)

if(n > 1e8) stop("n too large")

primes = rep(TRUE, n)

primes[1] = FALSE

last.prime = 2L

fsqr = floor(sqrt(n))

while (last.prime <= fsqr)

{

primes[seq.int(2L*last.prime, n, last.prime)] = FALSE

sel = which(primes[(last.prime+1):(fsqr+1)])

if(any(sel)){

last.prime = last.prime + min(sel)

}else last.prime = fsqr+1

}

which(primes)

}