Skip to main content

Project Euler problema 6

Lo lei, hice un oneliner en python y no lo corri porque pense que iba a demorar mucho, trate de recordar alguna propiedad pero no me acorde nada, buscando en internet todas eran resoluciones de project euler asi que decidi correrlo por fuerza bruta, termino siendo rapido asi que no me esforce mas:

problema:

The sum of the squares of the first ten natural numbers is,

1^(2) + 2^(2) + ... + 10^(2) = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)^(2) = 55^(2) = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.



python:

>>> sum(xrange(1, 101)) ** 2 - sum(map(lambda x: x**2, xrange(1, 101)))
25164150

lisp:

[44]> (- (expt (apply #'+ (loop for x from 1 to 100 collect x)) 2) (apply #'+ (loop for x from 1 to 100 collect (expt x 2))))
25164150

erlang:

-module(ej_006).
-export([show/0]).

do_to_range(Stop, Stop, Accum, Fun) -> Accum + Fun(Stop);
do_to_range(Start, Stop, Accum, Fun) ->
do_to_range(Start + 1, Stop, Accum + Fun(Start), Fun).

show() ->
SumOfSquares = do_to_range(1, 100, 0, fun(X) -> X * X end),
SquareOfSums = math:pow(do_to_range(1, 100, 0, fun(X) -> X end), 2),
SquareOfSums - SumOfSquares.



observaciones:
  • encontre esta referencia de lisp: http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node81.html
  • la exponenciacion en lisp se hace con expt
  • no encontre algo como xrange asi que use el macro de for
  • no me gusta la cantidad de funciones que hay en lisp (y en un solo namespace! :P)
  • en erlang lo hice un poco mas prolijito porque lo tuve que hacer recursivo
  • si no fuera por que python no tiene notacion prefija, la resolucion seria casi igual (si hiciese una funcion range con los for)

Comments

Comments powered by Disqus