Module: PrimeProducts::PrimeNumbers

Defined in:
lib/prime_products/prime_numbers.rb

Constant Summary collapse

INFINITY =
(1.0 / 0)

Class Method Summary collapse

Class Method Details

.first(number_of_primes) ⇒ Immutable::SortedSet<Integer>

Finds the first ‘n` prime numbers using a naive, but easy to understand, method. Alternative solutions are easy to find and implement.

However, I am opting to stick with a simpler more friendly option to keep complexity low, given that __we will be displaying results on a screen__, making it unlikely that you will show huge quantities.

Despite being a naive solution, this is still moderately performant. On my machine:

  • finding the first 10 takes ~0.00004s

  • finding the first 100 takes ~0.001s

  • finding the first 1000 takes ~0.2s

  • finding the first 10000 takes ~31s

It is unlikely that you would want a table of more than 1000, which only takes ~0.2 seconds. If we wanted to use these numbers elsewhere, and needed more, then I would optimise this code.

Parameters:

  • n (Integer)

    the number of prime numbers, starting from 0, you want to find

Returns:

  • (Immutable::SortedSet<Integer>)

    the first ‘n` prime numbers



29
30
31
32
33
34
35
36
37
38
# File 'lib/prime_products/prime_numbers.rb', line 29

def self.first(number_of_primes)
  # In Ruby 2.6, you can generate a Range up to infinity with `(2..)` 😍
  primes = (2..INFINITY).
    lazy.
    reject { |i| (2...i).any? { |divisor| (i % divisor).zero? } }.
    take(number_of_primes).
    to_a

  Immutable::SortedSet[*primes]
end