examples/primes/lib/primes/sieve_of_eratosthenes.rb in royw-drbman-0.0.2 vs examples/primes/lib/primes/sieve_of_eratosthenes.rb in royw-drbman-0.0.3
- old
+ new
@@ -50,25 +50,32 @@
result
end
private
+ # recursive prime calculation
+ # @param maximum (see #initialize)
+ # @param [Drbman] drbman the drb manager instance
+ # @return [Array<Integer>] the array of primes
def primes(maximum, drbman)
indices = []
if maximum > 2
composites = calc_composites(maximum, drbman)
flat_comps = composites.flatten.uniq
indices = calc_indices(flat_comps, maximum)
end
indices
end
- # when n = 20
- # sqr_primes = [2,3]
- # composites = [[2*2, 2*3, 2*4,...,2*9], [3*2, 3*3, 3*4,...,3*6]]
- # returns Array
+ # find the composites array
+ # @param maximum (see #initialize)
+ # @param drbman (see #primes)
+ # @return [Array<Integer>] the composites array
def calc_composites(maximum, drbman)
+ # when n = 20
+ # sqr_primes = [2,3]
+ # composites = [[2*2, 2*3, 2*4,...,2*9], [3*2, 3*3, 3*4,...,3*6]]
sqr_primes = primes(Math.sqrt(maximum).to_i, drbman)
composites = []
threads = []
mutex = Mutex.new
sqr_primes.each do |ip|
@@ -85,9 +92,12 @@
end
threads.each {|thrd| thrd.join}
composites
end
+ # sift the indices to find the primes
+ # @param [Array<Integer>] flat_comps the flattened composites array
+ # @param maximum (see #initialize)
def calc_indices(flat_comps, maximum)
indices = []
flags = Array.new(maximum, true)
flat_comps.each {|i| flags[i] = false}
flags.each_index {|i| indices << i if flags[i] }