This is the fourth of a series of short posts in which I solve interview questions from my Professional Practices course using Ruby.

The Prompt

Sexy prime numbers are prime numbers that differ by six. Examples would be 7 and 13, 11 and 17, and so on. Find all of the pairs of sexy prime numbers up to 500.

The Solution

The simplest solution is to use the ‘prime’ library that is included with Ruby by default:

require 'prime'

(1..500).each do |num|
  if Prime.prime?(num)
    numPlusSix = num + 6;
    if Prime.prime?(numPlusSix)
      puts [num, numPlusSix].to_s
    end
  end
end

Here is another way to solve the problem without requiring any libraries:

def isPrime?(number)
  case number
  when 1
    false
  when 2
    true
  else
    (2...number).each do |x|
      if number % x == 0
        return false
      end
    end
    return true;
  end
end

(1..500).each do |num|
  if isPrime?(num)
    numPlusSix = num + 6;
    if isPrime?(numPlusSix)
      puts [num, numPlusSix].to_s
    end
  end
end