Skip to content

Instantly share code, notes, and snippets.

@narenaryan
Created June 25, 2015 18:37
Show Gist options
  • Save narenaryan/cc7800ce6aacb515259b to your computer and use it in GitHub Desktop.
Save narenaryan/cc7800ce6aacb515259b to your computer and use it in GitHub Desktop.
A Sieve of Eratosthenes implementation in Julia
# Sieve of Eratosthenes, docstrings coming in Julia 0.4
function es(n::Int64) # accepts one 64 bit integer argument
isprime = ones(Bool, n) # n-element vector of true-s
isprime[1] = false # 1 is not a prime
for i in 2:int64(sqrt(n)) # loop integers from 2 to sqrt(n), explicit conversion to integer
if isprime[i] # conditional evaluation
for j in (i*i):i:n # sequence from i^2 to n with step i
isprime[j] = false # j is divisible by i
end
end
end
return filter(x -> isprime[x], 1:n) # filter using anonymous function
end
@salma-rodriguez
Copy link

Nicely done program. I have made an update to an inexact error that was being thrown by the compiler on my machine, due to the sqrt function. I also fixed a typo. You can fork from my repo if you'd like to include my changes in your project. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment