How do I generate the first n prime numbers?

前端 未结 15 1685
再見小時候
再見小時候 2021-02-02 09:57

I am learning Ruby and doing some math stuff. One of the things I want to do is generate prime numbers.

I want to generate the first ten prime numbers and the first ten

15条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-02 11:00

    If you'd like to do it yourself, then something like this could work:

    class Integer < Numeric
        def is_prime?
            return false if self <= 1
            2.upto(Math.sqrt(self).to_i) do |x|
                return false if self%x == 0
            end 
            true
        end 
    
        def next_prime
            n = self+1
            n = n + 1 until n.is_prime?
            n   
        end 
    end
    

    Now to get the first 10 primes:

    e = Enumerator.new do |y|
        n = 2
        loop do
            y << n
            n = n.next_prime
        end
    end
    
    primes = e.take 10
    

提交回复
热议问题