/* Problem 2 http://projecteuler.net/index.php?section=problems&id=2 """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do not exceed four million. """ Answer: 4613732 */ % | ?- L @= [F : N in 1..10, [F], fib(N,F)] % L = [1,2,3,5,8,13,21,34,55,89] % Even valued terms % | ?- L @= [F : N in 1..10, [F], (fib(N,F), F mod 2 =:= 0)] % L = [2,8,34] % The 4000000 limit % We know that 1..32 is enough... % | ?- L @= [[N,F]: N in 1..100, [F], (fib(N,F), F =< 4000000)] % L = [[1,1],[2,2],[3,3],[4,5],[5,8],[6,13],[7,21],[8,34],[9,55],[10,89],[11,144],[12,233],[13,377],[14,610],[15,987],[16,1597],[17,2584],[18,4181],[19,6765],[20,10946],[21,17711],[22,28657],[23,46368],[24,75025],[25,121393],[26,196418],[27,317811],[28,514229],[29,832040],[30,1346269],[31,2178309],[32,3524578]] go :- L = [ euler2a, euler2b, euler2c ], foreach(E in L, proc(E)). proc(E) :- write(E),write(':'), time(call(E)), nl. :-table fib/2. fib(0, 1) :- !. fib(1, 1) :- !. fib(N,F) :- N1 is N-1, N2 is N-2, fib(N1,F1), fib(N2,F2), F is F1+F2. euler2a :- Sum #= sum([F : N in 1..100, [F], (fib(N,F), F < 4000000, F mod 2 =:= 0)]), writeln(Sum). % This generates a list of all fib numbers < 4000000 p2(Total) :- p2(1, 1, Total), !. % p2(_, F, F) :- F > 4000000, !. % not needed % Some trickery to remove last element. p2(C, _, [F2|Total]) :- fib(C, F2), (F2 < 4000000 -> p2(C+1, F2, Total) ; Total = [] ). euler2b :- p2(Total), % get all < 4000000 L @= [F : F in Total, (F mod 2 =:= 0)], Sum #= sum(L), writeln(Sum). % This is just playing with arrays. Though it's not a really good % way to solve this problem. euler2c :- Len = 33, length(L, Len), L[1] @:=1, L[2] @:= 2, % Note: Must use "is" in the body. (I had expected to use @:=/2) foreach(N in 3..Len, L[N] is L[N-1] + L[N-2]), Sum #= sum([F : F in L, (F mod 2 =:= 0, F =< 4000000)]), writeln(Sum).