Last active
August 29, 2015 13:56
-
-
Save havenwood/9046302 to your computer and use it in GitHub Desktop.
Prime Number Chemistry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://users.minet.uni-jena.de/~dittrich//p/Dit2005upp.pdf | |
# https://github.com/videlalvaro/erlang-prime-sieve | |
require 'mathn' | |
module ChemicalPrime | |
def self.take n | |
sequence(n).map { |n| n * 2 + 1 }.unshift 2 | |
end | |
private | |
def self.sequence tail | |
cycle.take_while do |x, y| | |
y < tail && tail < Math.sqrt(2 * y + 1) && n % tail != tail.pred / 2 | |
end.each_with_object(1.upto(tail)) do |(x, y), enum| | |
enum = seive numbers, x, y | |
end | |
end | |
def self.cycle | |
1.upto(Float::INFINITY). | |
lazy. | |
with_object([0, 1]). | |
map { |n, (x, y)| [x + 1 * n, y + 2 * n] } | |
end | |
def self.seive enum, x, y | |
enum.reject do |n| | |
n % y == x && n > y | |
end | |
end | |
end | |
require 'benchmark' | |
ROUNDS = 1_000_000 | |
chemical = Benchmark.measure { ChemicalPrime.take ROUNDS }.real | |
regular = Benchmark.measure { Prime.take ROUNDS }.real |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment