Sieve of Eratosthenes in Ruby

前端 未结 5 1907
眼角桃花
眼角桃花 2020-12-14 20:10

Rather than scraping a Ruby version of this algorithm off the net I wanted to create my own based on its description here. However I cannot figure out two things

<         


        
5条回答
  •  [愿得一人]
    2020-12-14 20:32

    The following seems to work. I took out the floating point arithmetic and squared instead of square rooting. I also replaced the deletion loop with a "select" call.

    while primes[index]**2 <= primes.last
          prime = primes[index]
          primes = primes.select { |x| x == prime || x%prime != 0 }
          index += 1
    end
    

    Edit: I think I figured out how you're trying to do this. The following seems to work, and seems to be more in line with your original approach.

    while Math.sqrt(primes.last).ceil >= primes[index]
        (primes[index] * 2).step(primes.last, primes[index]) do
          |x|
          primes.delete(x)
        end
        index += 1
    end
    

提交回复
热议问题