Problem 6 är ett problem som får en mycket vacker lösning med funktionell kod.
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + … + 10^2 = 385The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)^2 = 55^2 = 3025Hence 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.
Det finns en ganska självklar väg till att lösa detta problem. Räkna ut de båda summorna och subtrahera.
-module(problem_6). -export([problem_6/0]). problem_6() -> Start = os:timestamp(), SumOfSquares = [X*X || X <- lists:seq(1, 100)], Sum = lists:sum(lists:seq(1, 100)), Res = (Sum*Sum) - lists:sum(SumOfSquares), io:format("Resultatet är ~poch det tog ~p sekunder att beräkna~n", [Res, timer:now_diff(os:timestamp(), Start)/1000000]).
Koden finns även på github.