Skip to content

Instantly share code, notes, and snippets.

@Nakilon
Created September 7, 2015 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nakilon/dfa6140dc98d976d5655 to your computer and use it in GitHub Desktop.
Save Nakilon/dfa6140dc98d976d5655 to your computer and use it in GitHub Desktop.
Crystal "almost" solution to Project Euler 111
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? = -> {
primes = [2, 3, 5] of Int32
candidate = 5
step = 4
-> (n : Int64) {
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
raise "3" unless prime?.call 3_i64
raise "4" if prime?.call 4_i64
raise "5" unless prime?.call 5_i64
raise "6" if prime?.call 6_i64
raise "7" unless prime?.call 7_i64
raise "8" if prime?.call 8_i64
raise "9" if prime?.call 9_i64
raise "10" if prime?.call 10_i64
raise "11" unless prime?.call 11_i64
n = 6
r = (0..9).map do |i|
s = 0
g = 2
x = (10**(n-1) - 1).to_i64
while x < 10**n
z = x += 2
m = 0
until z == 0
z, b = z.divmod 10
m += 1 if b == i
end
next if g > m
next unless prime?.call x
next s += x unless m > g
s = x
g = m
end
s
end
p r.sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment