Prime time

In this exercise, the task is to determine whether a number is prime or not. To do so, first I have got to think about what makes a prime number, here are a few requirements in my mind:

  • Not negative

  • Not 0

  • Not 1

  • Can divide by 1 and itself

  • Can not divide by other numbers such as 2, 3, 5, etc

    At first, i thought about whether or not i should go about dividing this number to every other prime that i can think of; but then what if i miss one?

Source: ImgFlip

Source: ImgFlip

SourceL ImgFlip

SourceL ImgFlip

Ok, one thing first - I need to check to see if num is a positive > 1. Because no matter what people say, 1 is not a prime number. Sad but true.

To iterate through and harness the power of CPU, I need to go through each of the number from 2 to less than num integer to determine if num is divisible.

The code is then below. If you’re studying, this is the part where I tell you there is a spoiler alert.

[ ]

[ ]

[ ]

def prime?(num)
  if num <= 1
    return false
  else
    (2..(num-1)).each do |n|
      return false if num % n == 0
        n += 1
      end
      true
  end
end

This exercise has been fun to do because I learned a new way to create a range of number for iteration (x..y). Onward!