Skip to content

Instantly share code, notes, and snippets.

@Nakilon
Last active September 7, 2015 00:27
Show Gist options
  • Save Nakilon/164360d5c8f952869f1d to your computer and use it in GitHub Desktop.
Save Nakilon/164360d5c8f952869f1d to your computer and use it in GitHub Desktop.
prime? method (in fact a lambda) implemented in Crystal
macro break_if_enough divisible, divisor, to_return = nil
q, r = {{divisible}}.divmod {{divisor}}
{% if to_return %}
return false if r == 0
return true if q <= {{divisor}}
{% else %}
break false if r == 0
break true if q <= {{divisor}}
{% end %}
end
prime? = -> {
# this array permanently stores table of primes up to the sqrt() of the nunmber you are checking
primes = [2, 3, 5] of Int32
candidate = 5
step = 4
-> (n : Int64) {
# return false if n < 2
primes.each do |prime|
break_if_enough n, prime, :return
end
loop do
loop do
candidate += step = 6 - step
break if primes.each do |prime|
break_if_enough candidate, prime
end
end
primes << candidate
break_if_enough n, candidate
end
}
}.call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment