Skip to content

Instantly share code, notes, and snippets.

@seankross
Last active October 20, 2022 17:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seankross/5946396 to your computer and use it in GitHub Desktop.
Save seankross/5946396 to your computer and use it in GitHub Desktop.
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