How do I generate the first n prime numbers?

前端 未结 15 1894
再見小時候
再見小時候 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

    In Ruby 1.9 there is a Prime class you can use to generate prime numbers, or to test if a number is prime:

    require 'prime'
    
    Prime.take(10) #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
    Prime.take_while {|p| p < 10 } #=> [2, 3, 5, 7]
    Prime.prime?(19) #=> true
    

    Prime implements the each method and includes the Enumerable module, so you can do all sorts of fun stuff like filtering, mapping, and so on.

提交回复
热议问题