Created
July 14, 2012 13:28
-
-
Save visibletrap/3111319 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
This file contains hidden or 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
prime = -> a=[false, false], z=1 do | |
n = a.size + 1 | |
b = a + [true] | |
(2..Math.sqrt(a.size)).each do |i| | |
if b[i] | |
x = 0 | |
while (y = i**2+x*i) < n | |
b[y] = false | |
x += 1 | |
end | |
end | |
end | |
r = (2..(n-1)).select{ |i| b[i] }.last | |
if z == r | |
prime[b, z] | |
else | |
puts r | |
-> { prime[b,r] } | |
end | |
end | |
# Output | |
> prime[][][][][][][][][][][][][][][][][][][][][][][][][] | |
2 | |
3 | |
5 | |
7 | |
11 | |
13 | |
17 | |
19 | |
23 | |
29 | |
31 | |
37 | |
41 | |
43 | |
47 | |
53 | |
59 | |
61 | |
67 | |
71 | |
73 | |
79 | |
83 | |
89 | |
97 |
This file contains hidden or 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
def all_prime_in(n) | |
a = [true]*n | |
(2..Math.sqrt(n)).each do |i| | |
if a[i] | |
x = 0 | |
while (y = i**2+x*i) < n | |
a[y] = false | |
x += 1 | |
end | |
end | |
end | |
(2..(n-1)).select { |i| a[i] } | |
end | |
def max_prime_in(n) | |
all_prime_in(n).last | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment