Skip to content

Instantly share code, notes, and snippets.

@ihercowitz
Created January 11, 2012 13:30
Show Gist options
  • Save ihercowitz/1594652 to your computer and use it in GitHub Desktop.
Save ihercowitz/1594652 to your computer and use it in GitHub Desktop.
Erlang - Goldbach's conjecture - http://en.wikipedia.org/wiki/Goldbach%27s_conjecture
%Demonstrates the Goldbach's conjecture - Every even integer greater than 2 can be expressed as the sum of two primes
%
% author: Bruno Jessen
%
-module(goldbach).
-export([primes/1, goldbach/1]).
%get all the primes using the classical sieve of eratosthenes
primes(N) ->
sieve([], lists:seq(2, N)).
sieve(P, [H|T]) ->
sieve(P ++ [H], [X || X <- T, X rem H /= 0]);
sieve(P, []) -> P.
goldbach(N) when N < 3 ; N rem 2 =/= 0 ->
[not_a_valid_goldbach_number];
goldbach(N) ->
Primes = primes(N),
goldbach(N, Primes, []).
goldbach(_, [], Acc) ->
Acc;
goldbach(N, L, Acc) ->
[H|T] = L,
R = N - H,
% io:format("H = ~p, T = ~p => member of ~p:~p ~n",[H, R, L, lists:member(R, L)]),
NewAcc = lists:append(Acc, [{H,R} || lists:member(R, L)] ),
goldbach(N, T, NewAcc).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment