Skip to content

Instantly share code, notes, and snippets.

@visibletrap
Created July 14, 2012 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save visibletrap/3111319 to your computer and use it in GitHub Desktop.
Save visibletrap/3111319 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
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
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