Created
January 11, 2012 13:30
-
-
Save ihercowitz/1594652 to your computer and use it in GitHub Desktop.
Erlang - Goldbach's conjecture - http://en.wikipedia.org/wiki/Goldbach%27s_conjecture
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
%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