Reputation: 349
I am new to Ruby. I want to know how to get the sum of all prime numbers below 1000. Code below prints out all the prime numbers between 1 to 1000.
require 'prime'
p = Prime.new
(1..1000).each do |n|
q = p.next()
puts "#{n}: #{q}"
end
How do I find the sum of those prime numbers. Appreciate your help
Upvotes: 0
Views: 1971
Reputation: 7405
Prime.new is obsolete. Now Prime has the default instance and you can access it as Prime.instance.
For convenience, each instance method of Prime.instance can be accessed as a class method of Prime.
So, your refactored prime printing code would be:
Prime.each(1000).with_index { |p, i| puts "#{i+1}: #{p}" }
#=>
1: 2
2: 3
3: 5
4: 7
5: 11
...
...
And to finding the sum:
Prime.each(1000).reduce(:+)
#=> 76127
Upvotes: 1