Class: PrimeSieve
- Inherits:
-
Object
- Object
- PrimeSieve
- Defined in:
- lib/prime_sieve.rb
Instance Attribute Summary collapse
-
#primes ⇒ Array<Integer>
readonly
Frozen array of prime numbers up to the pre-calculation limit.
Instance Method Summary collapse
-
#initialize(precalculation_limit = 10**7) ⇒ PrimeSieve
constructor
Create a new PrimeSieve.
-
#prime?(number) ⇒ Boolean
Determines whether the given number is prime.
Constructor Details
#initialize(precalculation_limit = 10**7) ⇒ PrimeSieve
Create a new PrimeSieve.
generate prime numbers up to this value integer
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
#primes ⇒ Array<Integer> (readonly)
Frozen array of prime numbers up to the pre-calculation limit.
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.
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 |