Skip to content

Instantly share code, notes, and snippets.

@ta1kt0me
Created March 17, 2016 04:29
Show Gist options
  • Select an option

  • Save ta1kt0me/010d609584bb5f8e25c2 to your computer and use it in GitHub Desktop.

Select an option

Save ta1kt0me/010d609584bb5f8e25c2 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
STDIN.read.split("\n").map {|i| i.chomp.to_i}.each do |n|
x = n
# lst = (3..x).to_a.select(&:odd?).unshift(2)
lst = (2..x).to_a
result = []
sqrt = Math.sqrt(x)
loop do
elem = lst.shift
result << elem
break if elem >= sqrt
lst.delete_if { |i| i % elem == 0 }
end
puts (result + lst).count
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment