How do I generate the first n prime numbers?

前端 未结 15 1724
再見小時候
再見小時候 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题