Class: PrimeSieve

Inherits:
Object
  • Object
show all
Defined in:
lib/prime_sieve.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(precalculation_limit = 10**7) ⇒ PrimeSieve

Create a new PrimeSieve.

generate prime numbers up to this value integer

Parameters:

  • precalculation_limit (#to_i) (defaults to: 10**7)

    calculate primality lookup, and

Raises:



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/prime_sieve.rb', line 16

def initialize(precalculation_limit = 10**7)
  @precalculation_limit = precalculation_limit.to_i
  @precalculation_limit > 0 or
    raise Ulaminate::TypeError, "#{@precalculation_limit} must be positive"

  @is_prime = ~Bitset.new(@precalculation_limit + 1)
  @is_prime.clear(0, 1)
  @primes = []

  2.upto(@precalculation_limit) do |i|
    next unless @is_prime[i]

    (i**2..@precalculation_limit).step(i) do |j|
      @is_prime[j] = false
    end

    primes << i
  end

  @primes.freeze
end

Instance Attribute Details

#primesArray<Integer> (readonly)

Frozen array of prime numbers up to the pre-calculation limit.

Returns:

  • (Array<Integer>)


8
9
10
# File 'lib/prime_sieve.rb', line 8

def primes
  @primes
end

Instance Method Details

#prime?(number) ⇒ Boolean

Determines whether the given number is prime.

Parameters:

  • number (#to_i)

Returns:

  • (Boolean)

    whether number is prime

Raises:



43
44
45
46
47
48
49
# File 'lib/prime_sieve.rb', line 43

def prime?(number)
  n = number.to_i
  n > 0 or raise Ulaminate::TypeError, "#{n} must be positive"

  return @is_prime[n] if n <= @precalculation_limit
  primes.all? { |prime| n % prime != 0 }
end