Skip to content

Instantly share code, notes, and snippets.

@dbhalling
Last active August 24, 2018 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbhalling/6fc826f12865e8edd162f51bbbd5f47e to your computer and use it in GitHub Desktop.
Save dbhalling/6fc826f12865e8edd162f51bbbd5f47e to your computer and use it in GitHub Desktop.
Semiprimes within range Codility33
#codility33 CountSemiprimes
# 4, 6, 9, 10, 14, 15, 21, 22, 25, 26 semiprimes
require 'prime'
p = [1, 4, 16]
q = [26, 10, 20]
def solution(p, q)
# first find all the primes less that 1/2 of q.max and use it to calculate the relevant semiprimes
qmax = q.max
primeArray = []
Prime.each(q.max/2) do |prime|
primeArray.push(prime)
end
p primeArray
resultArray = []
i = 0
# create two instances of primeArray and then multiple all the terms to form semiprimes
a = primeArray
b = a
while i < primeArray.count
y = 0
while y < a.count
val = a[i] * b[y]
resultArray.push(val)
y += 1
end
i += 1
end
# Remove dulipates and order the resultArray
resultArray.uniq!.sort!
# Eliminate all the semiprimes above q.max as they cannot be within the range
semiprimeArray = resultArray.take_while { |n| n <= q.max }
# find semiprimes within the range between p[j] and q[j] then count and place in countArray
countArray = []
j = 0
while j < q.count
truncatedArray = semiprimeArray.take_while { |n| n >= p[j] && n <= q[j] }
countArray = countArray.push(truncatedArray.count)
j += 1
end
return countArray
end
p "The semiprime count array is #{solution(p,q)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment