Last active
October 20, 2022 17:09
-
-
Save seankross/5946396 to your computer and use it in GitHub Desktop.
Counting primes using the Sieve of Eratosthenes in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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