Skip to content

Instantly share code, notes, and snippets.

@dbhalling
Created August 26, 2018 05:57
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/a6da1e3553c4a3f7f5011ed2969894bb to your computer and use it in GitHub Desktop.
Save dbhalling/a6da1e3553c4a3f7f5011ed2969894bb to your computer and use it in GitHub Desktop.
#codality35 CommonPrimeDivisors
#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