Skip to content

Instantly share code, notes, and snippets.

@adrianomitre
Last active February 24, 2016 18:14
Show Gist options
  • Save adrianomitre/5d1c13edc5ff28b56cea to your computer and use it in GitHub Desktop.
Save adrianomitre/5d1c13edc5ff28b56cea to your computer and use it in GitHub Desktop.
Circular Primes
# Ruby solution to http://www.beatmycode.com/challenge/5/show
class Integer # in real apps should use refinements instead of monkey patching
def prime?
return false if self < 2
! 2.upto(self**0.5).any? { |n| self % n == 0 }
end
def rotations
n, ss = to_s.length, to_s * 2
0.upto(n-1).map { |offset| ss[offset, n].to_i }
end
def circular_prime?
s = to_s
return false if self > 5 && s =~ /[02458]/
return false if self > 3 && s.each_char.map(&:to_i).inject(:+) % 3 == 0
self.rotations.all?(&:prime?)
end
end
module CircularPrimes
def self.upto(upper_limit)
1.upto(upper_limit).select(&:circular_prime?)
end
end
if __FILE__ == $0
max_n = ARGV[0]&.to_i || 1_000_000
v = CircularPrimes.upto(max_n)
puts "There are #{v.count} circular primes between 1 and #{max_n}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment