How do I generate the first n prime numbers?

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

提交回复
热议问题