Created
August 26, 2018 05:57
-
-
Save dbhalling/a6da1e3553c4a3f7f5011ed2969894bb to your computer and use it in GitHub Desktop.
#codality35 CommonPrimeDivisors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#codality35 CommonPrimeDivisors | |
require 'prime' | |
a = [15, 10, 3, 2] | |
b = [75, 30, 5, 8] | |
def solution(a, b) | |
if a.max > b.max | |
max = a.max | |
else | |
max = b.max | |
end | |
primeArray = [] | |
Prime.each(max/2) do |prime| | |
primeArray.push(prime) | |
end | |
result = "" | |
i = 0 | |
while i < a.count | |
factorArrayA = [] | |
if primeArray.include?(a[i]) | |
factorArrayA.push(a[i]) | |
else | |
truncatedArray = primeArray.take_while { |n| n <= a[i] / 2 } | |
# We only need to check primes that are 1/2 the size of the selected number from the array | |
# Then we check each if each of the primes are factors of the number | |
truncatedArray.each do |prime| | |
if a[i].modulo(prime) == 0 | |
factorArrayA.push(prime) | |
end | |
end | |
end | |
# I do the same logic for the b array. This is not dry buy I do not see a good answer right now | |
factorArrayB = [] | |
if primeArray.include?(b[i]) | |
factorArrayB.push(b[i]) | |
else | |
truncatedArray = primeArray.take_while { |n| n <= b[i] / 2 } | |
truncatedArray.each do |prime| | |
if b[i].modulo(prime) == 0 | |
factorArrayB.push(prime) | |
end | |
end | |
end | |
if factorArrayB == factorArrayA | |
result = result + "(#{a[i]}, #{b[i]})" | |
end | |
i += 1 | |
end | |
return result | |
end | |
puts "These pairs have common factors #{solution(a, b)}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment