class PrimeTable::GetPrimes
Helper class to extract the prime numbers.
Public Class Methods
fetch_primes(n)
click to toggle source
# File lib/prime_table.rb, line 8 def self.fetch_primes(n) collection = [] # will only run if the number of prime values to be fetched should be >= 1 # and keep on circling back unless fetch the number of prime numbers requested by requester. while collection.length < n # initialize the first prime number # and extracts the next prime number that needs to be evaluated i ||= 2 # push to the result set if number is found as prime number collection << i if self.validate_prime?(i) # extract the next prime number i += (i==2 ? 1 : 2) end if n >= 1 collection end
validate_prime?(num)
click to toggle source
check if the number is prime or not
# File lib/prime_table.rb, line 29 def self.validate_prime?(num) # use none enum so as to check if any of the iterator satisfies the block condition or not. (2..Math.sqrt(num)).none? { |i| (num % i).zero? } end