0

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?

7
  • 1
    Assuming you must store the values in an array, 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. Commented Dec 4, 2013 at 2:01
  • 1
    Compare your results to using the built in Prime class (ruby-doc.org/stdlib-1.9.3/libdoc/prime/rdoc/Prime.html). Then you might know if you can get it faster :) Commented Dec 4, 2013 at 2:03
  • 1
    For really large sum_prime, you could send request to a faster language. You could also make a few short cuts, by priming a hash with existing known values and starting from there: shortCut={100 => sum_prime(100), 1000 => sum_prime(1000), ad-nausum. Then you can just count from the least value and save your self quite a bit of ram. Commented Dec 4, 2013 at 2:04
  • 1
    @mr.musicman If it doesn't need to be in an array, then add each value to a sum += prime as soon as each prime is made available. Commented Dec 4, 2013 at 2:04
  • 2
    If your goal is just to sum primes, you might be better off downloading a list. Commented Dec 4, 2013 at 2:10

1 Answer 1

1

This should work. It uses others' suggestions:

require 'prime'
def sum_prime(limit)
  Prime.each(limit).inject(0) {|sum, num| sum + num}
end
puts sum_prime(200000)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.