How do I generate the first n prime numbers?

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

    Not related at all with the question itself, but FYI:

    • if someone doesn't want to keep generating prime numbers again and again (a.k.a. greedy resource saver)
    • or maybe you already know that you must to work with subsequent prime numbers in some way
    • other unknown and wonderful cases

    Try with this snippet:

      require 'prime'
    
      for p in Prime::Generator23.new
        # `p` brings subsequent prime numbers until the end of the days (or until your computer explodes)
        # so here put your fabulous code
        break if #.. I don't know, I suppose in some moment it should stop the loop
      end
      fp
    

    If you need it, you also could use another more complex generators as Prime::TrialDivisionGenerator or Prime::EratosthenesGenerator. More info

提交回复
热议问题