This function is not extremely complicated to implement and an easy approach (yet not extremely efficient as we shall see later) would be to check every single number from 2 up to 1 less than our number for divisiblity against the parameter of the function (remember that is the number enclosed within the brackets). So we start of declaring the body of our function: def is_prime(number) end Now, we want to check all the number starting from 2 all the way to our number minus 1 so we must use a range. Ruby ranges are declared as follows 2..5 (would give us a range containing all the numbers from 2 to 5). In general a..b would gives us a range from a all the way to b. A range is very similar to an array and it's a convenient way to generate a sequence of numbers: def is_prime(number)
for i in 2..(number-1)
end
end
end
We have declared our function and we have our for loop in the middle "giving us access" to all the numbers in between 2 and one less than our number so we check for divisilbity: def is_prime(number)
for i in 2..(number-1)
if(number % i) == 0
return 0
end
end
return 1
end Remember the percentage sign is called the "mod" operator and returns the rest from a division. So 9%4 = 1 and 10%5 = 0. Now the logic of our function is done: If at any point in our sequence of numbers there is a number that divides our parameter (that is if number % i equals 0) then we stop and return 0 because our number is not prime. We have no interest in knowing which number it is. Remember returning stops the function from executing. We return 1 if we get through the entire loop without ever returning 0 because that means that there is no number in our sequence which divides our number exactly. You could've had this return in an "else" block but there is no real need if you give it a bit of thought. Now I mentioned at the beginning that this is a naive approach so let me demonstrate why. If we have a number, let's say A and we assume that it has two factors B and C then either B or C has to be smaller than square root of A otherwise the product of B and C would be bigger. This means that we can only look for factors up to square root of A because we would "catch" the smaller factor first. So finally: def is_prime(number)
for i in 2..(Math.sqrt(number-1))
if(number % i) == 0
return 0
end
end
return 1
end