How do I generate the first n prime numbers?

前端 未结 15 1679
再見小時候
再見小時候 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 10:58
    class Numeric
      def prime?
        return self == 2 if self % 2 == 0
    
        (3..Math.sqrt(self)).step(2) do |x|
          return false if self % x == 0
        end
    
        true
      end
    end
    

    With this, now 3.prime? returns true, and 6.prime? returns false.

    Without going to the efforts to implement the sieve algorithm, time can still be saved quickly by only verifying divisibility until the square root, and skipping the odd numbers. Then, iterate through the numbers, checking for primeness.

    Remember: human time > machine time.

    0 讨论(0)
  • 2021-02-02 10:59

    Check out Sieve of Eratosthenes. This is not Ruby specific but it is an algorithm to generate prime numbers. The idea behind this algorithm is that you have a list/array of numbers say

    2..1000

    You grab the first number, 2. Go through the list and eliminate everything that is divisible by 2. You will be left with everything that is not divisible by 2 other than 2 itself (e.g. [2,3,5,7,9,11...999]

    Go to the next number, 3. And again, eliminate everything that you can divide by 3. Keep going until you reach the last number and you will get an array of prime numbers. Hope that helps.

    http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题