Problem Definition: Euler Problem 2

In order to solve this problem in python, I have used the yield keyword to implements a generator to provide a sequence of Fibonacci’s numbers. I think I can do a better work in using list comprehension in the main routine to filter and add up the even numbers, but the current version is basically good enough.

`“”“`

Euler 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 one million.

”“”

def gen_fib_seq():

a = 1

b = 2

yield a

yield b

try:

while 1:

c = a + b

a, b = b, c

yield c

except StopIteration:

pass

if **name** == “**main**”:

b = 0

onemillion = 1000000

for x in gen_fib_seq():

if x % 2 == 0:

if b + x < onemillion:

b = b + x

else:

break

print b

The erlang turns out to be even simpler than I thought. First of all, because every object or operation can be abstracted as a process, I do not need special keyword ‘yield’ to create a special object – generator. Furthermore the guard clause of function acc remove the need to put in any ‘if’ or ‘break’ to do, for example, the even number testing as in the python version.

`-module(p2).`

-export([main/0]).

start() –> spawn(fun() –> fib(0, 1) end).

fib(N, M) –>

receive

{Pid, next} –>

Pid ! {self(), N + M},

fib(M, N+ M)

end.

get_next_fib(Pid) –>

Pid ! {self(), next},

receive

{*, N} –>*

%% io:format(“~p~n”, [N])

N

end.

%% accumulator

acc(N, Pid, Acc) when (N rem 2) =:= 1 –>

N1 = get_next_fib(Pid),

acc(N1, Pid, Acc);

acc(N, Pid, Acc) when N + Acc < 1000000 –>

N1 = get_next_fib(Pid),

acc(N1, Pid, Acc + N);

acc(, _, Acc) –>

Acc.

%%%

%%% Program main()

%%%

main() –>

Pid = start(),

Acc = acc(1, Pid, 0),

Acc.