How to Implement a Prime Number Counting Algorithm in Ruby
In this lesson, we are going to create an algorithm that finds all prime numbers between zero to two million. Sounds exciting? In traditional programming languages, this algorithm would need a ton of code, but in Ruby we're going to see how to implement this efficiently.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide we are going to create an algorithm that finds all prime numbers between zero to two million. Sounds exciting? In traditional programming languages, this algorithm would need hundreds of lines of code, but in Ruby we're going to see how to implement this efficiently.

To start, let's get access to the prime library, and to do this, the code is:

require 'prime'

Next, we are going to store the prime numbers in an array with the code:

prime_array = Prime.take_while { |p| p < 2_000_000 }

In this code, we are creating a variable called prime_array. In this variable we are storing all the prime numbers up to 2,000,000.

devCamp Note: Ruby ignores underscores with integers, which is how we were able to represent the integer of 2 million with the syntax: 2_000_000. This is helpful when it comes to writing large numbers since we can use underscores instead of commas.

Before going further, let's just print the prime_array to see if it's working. If you execute the code, your output will have a huge set of numbers, since it has to print every prime number from zero to two million.

2
3
5
7
11
13
...
1999891
1999957
1999969
1999979
1999993

Now, if we want to add all the values in our array, we can do it by leveraging the inject method:

total_count = prime_array.inject { |sum, x| sum + x }

If you print this array and execute the file, the output should be 142913828922.

The entire code is:

require 'prime'

prime_array = Prime.take_while { |p| p < 2_000_000 }
total_count = prime_array.inject { |sum, x| sum + x }

puts total_count

So in this program we were able to implement a complex math solution with only a few lines of code using the power of functional programming in Ruby.