I have a simple method that finds prime numbers, puts them in an array and then sums them up. What are some possible steps to speed it up?
def prime?(number, array)
array.each do |x|
if number % x == 0
return false
end
end
true
end
def sum_prime(number)
i = 0
prime = 1
output = [2]
while prime < number
if prime?(prime, output)
i += 1
output << prime if prime != 1
p prime
end
prime += 2
end
output.inject(:+)
end
sum_prime(200000)
is array#each ok? Can I concatinate differently for faster results?
array.inject(:+)seems to be about as fast as one can do it in ruby. The only other suggestion would be to use a compiled language like C but even there the improvement will probably be negligible.sum += primeas soon as eachprimeis made available.