title: How do I efficiently sieve through a selected range for prime numbers?
body: <p>I've been working through <a href="https://projecteuler.net" rel="nofollow">Project Euler</a> and Sphere Online Judge problems. In this particular problem, I have to find all the prime numbers within two given numbers. I have a function that looks promising (based on the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">Sieve of Eratosthenes</a>), except it's too slow. Can someone spot what is slowing my function down so much, and hint at how I can fix it? Also, some comments about how to approach optimization in general (or links to such comments/books/articles etc,) would be greatly appreciated.</p>
  
  <p>Code:</p>
  
  <pre><code>def ranged_sieve(l, b)
    primes = (l..b).to_a
    primes[0]=nil if primes[0] &lt; 2
    (2..Math.sqrt(b).to_i).each do |counter|
      step_from = l / counter
      step_from = step_from * counter
      l &gt; 3 ? j = step_from : j = counter + counter
      (j..b).step(counter) do |stepped|
        index = primes.index(stepped)
        primes[index] = nil if index
      end
    end
    primes.compact
  end
  </code></pre>