# Finding Prime Numbers in Ruby

Code quizzes commonly have a prime number challenge, which got me to thinking, shouldn’t there already be an `is_prime`

method? Well, yes, there should be. And in Ruby, there is.

Ruby has a `Prime`

class and it does some useful things for you when you `require 'prime'`

in your file. Two of my favorites are:

#### Return true if a given number is prime

Awwwwww yeah! That’s the stuff right there.

#### Generate a list of primes starting with 2 through a given number

Those two methods alone have pretty much handled any prime number code challenge that’s comes my way. If the challenge is about researching a programming language to see what options are available, this approach wins – hooray!– because learning a language’s libraries and methods makes us stronger, faster, and more efficient. Ah yes, proficiency leads to efficiency… I like that.

#### Creating our own `is_prime`

method

But let’s be honest, code challenges involving math are usually focused on manipulating the *basics* of a language to solve a math problem, not about accessing the libraries or gems you’d probably use in real life. Code challenges like to make you do logic calisthenics, so let’s do this thing the hard way.

Here’s some pseudocode for my approach:

- Create a range of numbers from 2 to one less than the number in question (
`num - 1`

) - Loop through that range
- Ask if the number in question (
`num`

) is cleanly divisible by each number in the range (`n`

) - If any one of those range numbers (
`n`

) creates a 0 remainder when the number in question (`num`

) is divided by that number (`n`

), the number in question (`num`

) is not prime

- Ask if the number in question (
- If at the end of the loop, none of the range numbers (
`n`

) created a 0 remainder, the number in question (`num`

) is, indeed, prime

### And now for the actual code

#### Using the Ruby `each`

loop:

#### Using a Ruby `while`

loop:

The Ruby while loop approach might feel familiar to people coming to Ruby from JavaScript because its iteration is transparent like JavaScript’s for loop. After all, there’s none of that kludgy `(2..(num - 1))`

to define the iteration range like there is in the Ruby `each`

loop. For good measure, here is a JavaScript version of `isPrime`

.