Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Counting primes using the Sieve of Eratosthenes in R
# The Sieve of Eratosthenes
# Given a number greater than zero this function will return a list of primes between 2 and the number given as argument.
sieveOfEratosthenes <- function(num){
values <- rep(TRUE, num)
values[1] <- FALSE
prev.prime <- 2
for(i in prev.prime:sqrt(num)){
values[seq.int(2 * prev.prime, num, prev.prime)] <- FALSE
prev.prime <- prev.prime + min(which(values[(prev.prime + 1) : num]))
}
return(which(values))
}
sieveOfEratosthenes(2000)
length(sieveOfEratosthenes(2000)) # 303
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment