Project Euler problem 6

Sum square difference

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.
Link to original description
Source code examples on Github

Erlang version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname p6
% vim:syn=erlang

-mode(compile).

main(_) ->
    Answer = qs(),
    io:format("Answer: ~p ~n", [Answer]).

qs() -> qsi(1,{0,0}).
qsi(101,{A,B}) -> A*A - B;
qsi(N,{A,B})   -> qsi(N+1, {A+N, B + N*N}). 


Perl version

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/perl -w

use strict;

sub main{
    my ($a, $b) = (0, 0);
    for (1..shift){ $a+=$_; $b += $_*$_ }
    print "Answer: ".($a*$a - $b)."\n";
}

main(100);

Python version

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/python

def main():
    r = range(1,101)
    a = sum(r)
    answer = a*a - sum(x*x for x in r)
    print "Answer: %d" % answer

main()