HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Check sum of all primes under two million

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
millionprimesallundertwosumcheck

Problem

I'm exploring ruby by writing a code that checks the sum of all prime numbers under two million. As I am still in the process of learning ruby, I'm unfamiliar with all the standards and best practices. What I have so far works, but I am certain it can be improved. Where can I improve my code for both readability and speed?

def is_prime(n)
    range = n
    i = 2

    while i < range do
        return false if (n % i == 0)
        range = n / i
        i += 1
    end
    true
end

sum = 2
(3..2000000).each do |num|
    if (is_prime(num))
        #puts "#{num}"
        sum += num
    end
end

puts "#{sum}"

Solution

Ruby favours Functional Programming, let me show you an example.

def prime?(n)
  limit = Math.sqrt(n).to_i + 1
  (2..limit).all? { |i| n % i != 0 }
end


This improves readability as the code makes use of all? to implicitly loop (Instead you looped explicitly) and is faster as the limit is the sqrt of n and not n and all? short-circuits (returns as soon as one condition is false).

Also the second part would benefit from FP:

puts (2..2000000).select{ |n| prime?(n) }.inject(:+)


In general, in Ruby explicit looping is the exception and not the norm, as there are so many built-ins and shortcuts to make use of.

Each function I made use of here is listed at The Ruby Enumerable Documentation and I warmly suggest studying in detail that page, it will take a bit of time, but the time you will save in the future by using it instead of reinventing the wheel each time will be more than worth it.

Code Snippets

def prime?(n)
  limit = Math.sqrt(n).to_i + 1
  (2..limit).all? { |i| n % i != 0 }
end
puts (2..2000000).select{ |n| prime?(n) }.inject(:+)

Context

StackExchange Code Review Q#109265, answer score: 6

Revisions (0)

No revisions yet.