Thursday, April 18, 2013

Twin prime on Enumerator::Lazy

About twin prime : http://en.wikipedia.org/wiki/Twin_prime
irb(main):001:0> class Enumerator::Lazy
irb(main):002:1>   def at(nth)
irb(main):003:2>     self.drop(nth).first
irb(main):004:2>   end
irb(main):005:1>   def slice(lower, upper)
irb(main):006:2>     self.drop(lower).take(upper - lower + 1)
irb(main):007:2>   end
irb(main):008:1> end
=> nil
irb(main):009:0> require 'prime'
=> true
irb(main):010:0> twin_prime = Prime.lazy.each_cons(2).select{|p,r| r-p == 2}
=> #<Enumerator::Lazy: #<Enumerator::Lazy: #<Enumerator::Lazy: Prime>:each_cons(2)>:select>
irb(main):011:0> twin_prime.at 0
=> [3, 5]
irb(main):012:0> twin_prime.at 1
=> [5, 7]
irb(main):013:0> twin_prime.at 2
=> [11, 13]
irb(main):014:0> twin_prime.at 3
=> [17, 19]
irb(main):015:0> twin_prime.at 100
=> [3851, 3853]

No comments:

Post a Comment