Last active
July 15, 2016 20:00
-
-
Save ddresselhaus/94c6286a5ba0a80c2da3a07c529771d3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# https://projecteuler.net/index.php?section=problems&id=50 | |
defmodule Primes do | |
def primes(ceiling), do: Enum.filter(1..ceiling, fn x -> is_prime(x) end) | |
def is_prime(n), do: factors(n, div(n, 2)) == [1] | |
def factors(1, _), do: [1] | |
def factors(_, 1), do: [1] | |
def factors(n, i) do | |
if rem(n, i) == 0 do | |
[i|factors(n, i-1)] | |
else | |
factors(n, i-1) | |
end | |
end | |
def recursive_addition([], depth, total, ceiling), do: [ depth, total ] | |
def recursive_addition([prime|remainder], depth, total, ceiling) do | |
if (( total + prime) > ceiling ) do | |
[ depth, total ] | |
else | |
recursive_addition(remainder, depth + 1, total + prime, ceiling) | |
end | |
end | |
def primes_and_counts([], ceiling, high_score), do: high_score | |
def primes_and_counts([prime|remainder], ceiling, high_score) do | |
[count, total] = recursive_addition([prime|remainder], 0, 0, ceiling) | |
new_high_score = if count > high_score.count && Primes.is_prime(total) do | |
%{ prime: prime, total: total, count: count } | |
else | |
high_score | |
end | |
primes_and_counts(remainder, ceiling, new_high_score) | |
end | |
end | |
ceiling = 1_000_000 | |
primes = Primes.primes(ceiling) | |
answer = Primes.primes_and_counts(primes, ceiling, %{count: 0} ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment