Skip to content

Instantly share code, notes, and snippets.

@antimon2
Created June 18, 2012 13:50
Show Gist options
  • Select an option

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

Select an option

Save antimon2/2948462 to your computer and use it in GitHub Desktop.
Prime::A2Generator < Prime::PseudoPrimeGenerator
# original: http://log.ttsky.net/article/19515687.html
require 'prime'
class Prime
# An implementation of +Prime::PseudoPrimeGenerator+.
class A2Generator < PseudoPrimeGenerator
def initialize
@h = {}
@n = nil
@d = nil
super
end
def succ
if @n.nil?
@n = 1
return 2
elsif @d.nil?
@d = 4
return 3
end
n = @n
d = @d
while true
m = n += d
if (b = @h[n])
k = ((m + b) % 3 == 0) ? 2 : 4
k = 6 - k while @h[m += b*k]
@h[m] = b
@h.delete(n)
else
k = 4
k = 6 - k while @h[m += n*k]
@d = 6 - d
return @n = @h[m] = n
end
d = 6 - d
end
end
alias next succ
def rewind
initialize
end
end
end
if $0 == __FILE__
max = ARGV.size == 1 ? ARGV[0].to_i : 100
pr = 0
Prime.each(max, Prime::A2Generator.new){|num|pr=num}
puts "The max prime number (<=#{max}) is #{pr}."
pr = Prime.each(nil, Prime::A2Generator.new).take(max)[-1]
puts "The #{max}th prime number is #{pr}."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment