sábado, febrero 07, 2009

project euler - problema 2

La diferencia es que en python lo hice con generadores ya que queda mas prolijo, hasta donde se no hay generadores en los otros.

Python

# 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.

def fibonacci():
one = 0
two = 1
step = 1

while True:
one, two = two, one + two
yield two
step += 1

def calculate(limit):
result = 0
for value in fibonacci():
if value > limit:
break

if value % 2 == 0:
result += value

return result

def print_result():
print calculate(4000000)

if __name__ == '__main__':
print_result()



Erlang

-module(ej_002).
-compile(export_all).
%-export([calculate/1, print_result/0]).

fibonacci_step(First, Second) -> {Second, First + Second}.

calculate(First, Second, Limit) -> calculate(First, Second, Limit, 0).

calculate(_First, Second, Limit, Accum) when Second > Limit -> Accum;
calculate(First, Second, Limit, Accum) ->
{NewFirst, NewSecond} = fibonacci_step(First, Second),

case NewSecond rem 2 of
0 -> NewAccum = Accum + NewSecond;
1 -> NewAccum = Accum
end,

calculate(NewFirst, NewSecond, Limit, NewAccum).

calculate(Limit) -> calculate(0, 1, Limit).

print_result() -> io:format("~w~n", [calculate(4000000)]).


Lisp (note que los paréntesis dejan de molestar y si lo tabulas de una forma particular se parece mucho a python :D)

(defun fibonacci-step (one two)
(list two (+ one two)))

(defun calculate-helper (one two limit accum)
(cond ((> two limit) accum)
(T (let ((result (fibonacci-step one two)))
(let ((new-one (car result))
(new-two (cadr result)))

(if (eq (rem new-two 2) 0)
(calculate-helper new-one new-two limit (+ accum new-two))
(calculate-helper new-one new-two limit accum)))))))

(defun calculate (limit) (calculate-helper 0 1 limit 0))

(defun print-result () (print (calculate 4000000)))

No hay comentarios.:

Seguidores

Archivo del Blog