Ray
Ray

Reputation: 349

How to find the sum of all prime numbers less than 1000 in Ruby?

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

Answers (3)

Sharvy Ahmed
Sharvy Ahmed

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

karlingen
karlingen

Reputation: 14645

Simple as this:

Prime.each(1000).inject :+

Upvotes: 1

Santhosh
Santhosh

Reputation: 29144

Prime.each(1000).inject :+
# => 76127 

Upvotes: 1

Related Questions