Sieve of Eratosthenes in Ruby

前端 未结 5 1920
眼角桃花
眼角桃花 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:38

    This is a pretty straightforward implementation of the Wikipedia article pseudocode, using a bit array.

    #!/usr/bin/env ruby -w
    
    require 'rubygems'
    require 'bitarray'
    
    def eratosthenes(n)
    
       a = BitArray.new(n+1)
    
       (4..n).step(2) { |i|
          a[i] = 1
       }
    
       (3..(Math.sqrt(n))).each { |i|
           if(a[i] == 0)
               ((i*i)..n).step(2*i) { |j|
                   a[j] = 1
               }
           end
       }
       a
     end
    
    def primes(n)
        primes = Array.new
         eratosthenes(n).each_with_index { |isPrime, idx|
            primes << idx if isPrime == 0
         }
         primes[2..-1]
    end
    

提交回复
热议问题