Skip to content

Instantly share code, notes, and snippets.

@supermomonga
Created October 17, 2013 11:23
Show Gist options
  • Save supermomonga/7023233 to your computer and use it in GitHub Desktop.
Save supermomonga/7023233 to your computer and use it in GitHub Desktop.
def primes_to(x, ns = 2.upto(x).to_a, ps = [], to = Math.sqrt(x))
ns.first.tap { |p| break p.nil? ? 0 : p > to ? ps + ns : primes_to(x, ns.reject{ |n| n % p == 0 }, ps << p) }
end
def prime_count x
primes_to(x).size
end
[2, 5, 10, 19, 54, 224, 312, 616, 888, 977, 1000000].each do |x|
p prime_count(x - 1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment