Skip to content

Instantly share code, notes, and snippets.

@nimamehanian
Created March 5, 2013 21:54
Show Gist options
  • Save nimamehanian/5094678 to your computer and use it in GitHub Desktop.
Save nimamehanian/5094678 to your computer and use it in GitHub Desktop.
A predicate method that determines whether a number is prime. Useful for some of Project Euler's challenges.
class Integer
def prime?
if self.even? && self != 2 ||
self.send(:sum_of_digits_div_by_three?) && self != 3 ||
self.send(:last_two_digits_div_by_four?) ||
self.send(:last_digit_div_by_five?) && self != 5
return false
else
return true
end
end
private
def sum_of_digits_div_by_three?
sum = 0
self.to_s.split('').each do |digit|
sum += digit.to_i
end
sum % 3 == 0 ? true : false
end
def last_two_digits_div_by_four?
number = ''
digits = self.to_s.split('')
if digits.length >= 2
number << digits[-2] << digits[-1]
number.to_i % 4 == 0 ? true : false
else
false
end
end
def last_digit_div_by_five?
digits = self.to_s.split('')
digits[-1].to_i == 0 || digits[-1].to_i == 5 ? true : false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment