/* Euler #2 in Picat. Problem 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. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ main => time(go). go => euler2. euler2 => writeln(sum([F : N in 1..100, F = fibt(N), F < 4000000, F mod 2 =:= 0])). % from exs.pi table fibt(0)=1. fibt(1)=1. fibt(N)=F,N>1 => F=fibt(N-1)+fibt(N-2). euler2b => I = 1, Sum = 0, F = fibt(I), while (F < 400000) if F mod 2 == 0 then Sum := Sum + F end, I := I + 1, F := fibt(I) end, writeln(Sum). % % Using non tabled fib. Very slow. % euler2c => writeln(sum([F : N in 1..100, F = fibt2(N), F < 4000000, F mod 2 =:= 0])). % acumulator euler2d => e2d(1,4000000,0,0,S), println(S). e2d(_N,Limit,F, S1,S2) ?=> F >= Limit, S2 = S1. e2d(N,Limit,F,S1,S2) ?=> F < Limit, F2 = fibt(N), F2 mod 2 = 0, e2d(N+1,Limit,F2, S1+F,S2). e2d(N,Limit,F,S1,S2) => e2d(N+1,Limit,F,S1,S2). % Using break/1 (from about Picat version 3.1#6) euler2e => writeln(sum([F : N in 1..100, F = fibt(N), break(F >= 4000000), F mod 2 =:= 0])). % Not tabled % table fibt2(0)=1. fibt2(1)=1. fibt2(N)=F,N>1 => F=fibt2(N-1)+fibt2(N-2).