I have a Ruby program which should solve the following problem:
Consider the divisors of 30: 1,2,3,5,6,10,15,30. It can be seen that for every divisor d of 30, d+30/d is prime.
Find the sum of all positive integers n not exceeding 100 000 000 such that for every divisor d of n, d+n/d is prime.
require 'prime'
class Integer
def factors # returns an array of all factors of self
return (1..self).collect { |n| n if ((self/n) * n) == self }.compact
end
end
puts "Started at #{Time.now}."
counter = 0
1.upto(100000000) do |n|
factors = n.factors
counter += n if factors.all? { |d| ( (d+n) / d ).is_a? Prime }
end
p counter
puts "Ended at #{Time.now}."
Problem is, while the code runs, it takes so long (not finished after several hours) that I can't actually test if I get the right answer. Is there any way to make the code more efficient so that it completes in a shorter amount of time? The problem is question #357 of Project Euler. All Euler problems should take less than one minute to solve if an efficient algorithm is being used.