Skip to content

Instantly share code, notes, and snippets.

@antimon2
Created June 6, 2012 10:42
Show Gist options
  • Select an option

  • Save antimon2/2881237 to your computer and use it in GitHub Desktop.

Select an option

Save antimon2/2881237 to your computer and use it in GitHub Desktop.
Prime#twins
require 'prime'
class Prime
def twins n = nil
return to_enum :twins, n unless block_given?
each(n).each_cons(2) do |p1, p2|
yield [p1, p2] if p2 - p1 == 2
end
end
end
# Prime.twins.take(10)
# => [[3, 5], [5, 7], [11, 13], [17, 19], [29, 31], [41, 43], [59, 61], [71, 73], [101, 103], [107, 109]]
# Prime.twins(100).to_a
# => [[3, 5], [5, 7], [11, 13], [17, 19], [29, 31], [41, 43], [59, 61], [71, 73]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment